[
{name: "name", value: "John"}
{name: "last_name", value: "Snow"}
{name: "father_name", value: ""}
{name: "name", value: "Tony"}
{name: "last_name", value: "Stark"}
{name: "father_name", value: ""}
{name: "other_field", value: "damn"}
]
[{name: "John", father_name: "" ,last_name: "Snow" },
{name: "Tony", father_name: "" ,last_name: "Stark"}]
reduce()
объект триггеров с тремя ключами, по каждому из ключевых слов. Перед вставкой очередной пары с ключом из триггеров, переводить его в true. Если он до этого уже включён — значит, пора вставлять новый объект для заполнения.const data = [
{name: "name", value: "John"},
{name: "last_name", value: "Snow"},
{name: "father_name", value: ""},
{name: "name", value: "Tony"},
{name: "last_name", value: "Stark"},
{name: "father_name", value: ""},
{name: "other_field", value: "damn"},
];
data.reduce((acc, c) => {
if (true === acc.triggers[c.name]) {
Object.keys(acc.triggers).forEach((key) => acc.triggers[key] = false);
acc.arr.push({});
}
if (c.name in acc.triggers) acc.triggers[c.name] = true;
acc.arr[acc.arr.length - 1][c.name] = c.value;
return acc;
}, {
triggers: {
"name": false,
"last_name": false,
"father_name": false,
},
arr: [{}],
}).arr;
/*
[
{
"name": "John",
"last_name": "Snow",
"father_name": ""
},
{
"name": "Tony",
"last_name": "Stark",
"father_name": "",
"other_field": "damn"
}
]
*/
const arr = [
{name: "name", value: "John"},
{name: "last_name", value: "Snow"},
{name: "father_name", value: ""},
{name: "name", value: "Tony"},
{name: "last_name", value: "Stark"},
{name: "father_name", value: ""},
{name: "other_field", value: "damn"},
];
const newArr = [];
let obj = {};
arr.forEach(item => {
obj[item.name] = item.value;
if (item.name === 'father_name') {
newArr.push({...obj});
obj = {};
}
});