Reputation: 501
trying to loop over json and join specific values and further loop over them.
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++;
}
}
how can I join title with appropriate group of names to loop over newly created groups ?
newly created group1 should be
[
{title: "title1", type: "group1"},
{name: "name1", type: "in"},
{name: "name2", type: "out"},
{name: "name3", type: "out"}
]
and newly created group2 should be
[
{title: "title2", type: "group2"},
{name: "name4", type: "out"}
]
Upvotes: 1
Views: 37
Reputation: 386680
You could use title
property for checking if a new group has started. If so, then push the actual object in an array to the result set, otherwise push the actual object to the last array.
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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1