从json循环创建多维数组,在组中连接特定值

时间:2017-09-21 18:58:59

标签: javascript arrays

尝试遍历json并连接特定值并进一步循环它们。

var json = [
    {title: "title1", type: "group1"}
    {name: "name1", type: "in"}
    {name: "name2", type: "out"}
    {name: "name3", type: "out"}
    {title: "title2", type: "group2"}
    {name: "name4", type: "out"}
];

var obj = {},
    count = 0;

for (var i=0; i < json.length; i++){
    if('name' in json[i]){
        var obj[count].push(json[i])
    }else{
        count++;
    }
}

如何使用适当的名称组连接标题以循环新创建的组?

新创建的group1应为

[
    {title: "title1", type: "group1"},
    {name: "name1", type: "in"},
    {name: "name2", type: "out"},
    {name: "name3", type: "out"}
]

并且新创建的group2应为

[
    {title: "title2", type: "group2"},
    {name: "name4", type: "out"}
]

1 个答案:

答案 0 :(得分:1)

您可以使用title属性来检查新组是否已启动。如果是,则将数组中的实际对象推送到结果集,否则将实际对象推送到最后一个数组。

&#13;
&#13;
var array = [{ title: "title1", type: "group1" }, { name: "name1", type: "in" }, { name: "name2", type: "out" }, { name: "name3", type: "out" }, { title: "title2", type: "group2" }, { name: "name4", type: "out" }],
    result = array.reduce(function (r, o) {
        if ('title' in o) {
            r.push([o]);
        } else {
            r[r.length - 1].push(o);
        }
        return r;
    }, []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;