无法将完整的问题放在标题中。 我有一个对象数组,每个对象有两个键值。 第一个键值是一个字符串,第二个键是另一个对象数组。
我需要迭代这个数组,以便我只有唯一的主名称。 如果名称存在于新数组中,则只将相关数组推送到相应的对象。我希望这对于阅读本文的人有一定道理。
我希望迭代的数组示例:
[
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5c", id: 75, product_name: "product name"}]},
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5e", id: 89, product_name: "product name"}]},
{master: 'μHB MICRO HOMOGENIZER', related: [{_id: "59f5f1fe7d079b6be8fdef5r", id: 102, product_name: "product name"}]},
{master: 'μHB MICRO HOMOGENIZER', related: [{_id: "59f5f1fe7d079b6be8fdef5f", id: 67, product_name: "product name"}]},
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5z", id: 92, product_name: "product name"}]},
]
基于上面的数组,我希望得到一个如下所示的结果:
[
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5c", id: 75, product_name: "product name"}, {_id: "59f5f1fe7d079b6be8fdef5e", id: 89, product_name: "product name"},{_id: "59f5f1fe7d079b6be8fdef5z", id: 92, product_name: "product name"}]},
{master: 'μHB MICRO HOMOGENIZER', related: [{_id: "59f5f1fe7d079b6be8fdef5r", id: 102, product_name: "product name"}, {_id: "59f5f1fe7d079b6be8fdef5f", id: 67, product_name: "product name"}]},
]
非常感谢任何帮助,谢谢。
答案 0 :(得分:2)
你不需要使用underscore.js。
let objects = [
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5c", id: 75, product_name: "product name"}]},
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5e", id: 89, product_name: "product name"}]},
{master: 'μHB MICRO HOMOGENIZER', related: [{_id: "59f5f1fe7d079b6be8fdef5r", id: 102, product_name: "product name"}]},
{master: 'μHB MICRO HOMOGENIZER', related: [{_id: "59f5f1fe7d079b6be8fdef5f", id: 67, product_name: "product name"}]},
{master: 'Omni Mixer Homogenizer', related: [{_id: "59f5f1fe7d079b6be8fdef5z", id: 92, product_name: "product name"}]},
]
function process(object) {
let results = [];
objects.forEach(object => { // iterate through array
let result = results.find(x => x.master === object.master);
if (result) { // if item with "master" exists
object.related.forEach(item => { // add all realted items to existing items "related" array
if (!result.related.find(x => x._id === item._id)) {
result.related.push(item);
}
});
} else { // otherwise add an item to "results" array
results.push(object);
}
});
return results;
}
console.log(process(objects));