伙计们,请帮我很好地包装一组对象。
逻辑是这样的 - 一个没有的对象id(会有一个这样的)需要
features[<вложенный объект с name=="HEAD">].value
从另一个对象添加到它的值:具有相同的类型(也会有一个),但它有id.
我写了,但我不知道我的选择在性能方面是最优的。我知道你可以应用 reduce,但有些东西效果不太好。谢谢!!
let orders = [
{
type: "NEW",
features: [
{ value: ['aa', 'bb'], name: "URL" },
{ value: ['cc', 'dd'], name: "HEAD" }
]
}, {
id: "10",
type: "NEW",
features: [
{ value: ['ee', 'ff'], name: "URL" },
{ value: ['gg', 'hh'], name: "HEAD" }
]
}, {
id: "23",
type: "OLD",
features: [
{ value: ['ii', 'gg'], name: "URL" },
{ value: ['kk', 'll'], name: "HEAD" }
]
}, {
id: "55",
type: "OLD",
features: [
{ value: ['mm', 'nn'], name: "URL" },
{ value: ['oo', 'pp'], name: "HEAD" }
]
}
];
我的版本:
let orderWithNoid = orders.find(x => x.type === 'NEW' && !x.id);
let orderWithId = orders.find(x => x.type === 'NEW' && x.id);
const {
features: feat1
} = orderWithNoid;
const {
features: feat2
} = orderWithId;
for (let f1 of feat1) {
for (let f2 of feat2) {
if (f1.name === 'HEAD' && f1.name === f2.name) {
f1.value.push(...f2.value)
}
}
}
for (let order of orders) {
if (order.type === 'NEW' && !order.id) {
order.features = feat1;
}
}
你应该得到以下结构:
let result = [{
type: "NEW",
features: [
{ value: ['aa', 'bb'], name: "URL" },
{
value: ["cc", "dd", "gg", "hh"] // добавились 2 последних значения
name: "HEAD"
}
]
}, {
id: "10",
type: "NEW",
features: [
{ value: ['ee', 'ff'], name: "URL" },
{ value: ['gg', 'hh'], name: "HEAD" }
]
}, {
id: "23",
type: "OLD",
features: [
{ value: ['ii', 'gg'], name: "URL" },
{ value: ['kk', 'll'], name: "HEAD" }
]
}, {
id: "55",
type: "OLD",
features: [
{ value: ['mm', 'nn'], name: "URL" },
{ value: ['oo', 'pp'], name: "HEAD" }
]
}
];
在示例问题中,数据量非常小(数组中只有 4 个对象),用它来衡量性能是没有意义的,在我看来:几乎任何代码都会如此快速地完成任务,以至于差异不同执行选项之间的执行速度会接近误差。
一般来说,首先要做的是尽可能避免嵌套循环(增加循环次数)。JS 中其他相对昂贵的操作,它们本身并没有那么“慢”,但希望在周期内减少这些操作的数量:创建新的对象实例;来电;分枝; 使用复杂的正则表达式搜索和替换。这个列表当然不完整,理想情况下,在循环内部,值得尽可能少做任何操作:如果可以在循环之外完成某些事情,那么最好这样做:)