gpt4 book ai didi

javascript - 重构 map、reduce 和 double for 循环 - javascript es6

转载 作者:行者123 更新时间:2023-12-01 00:14:22 31 4
gpt4 key购买 nike

我有一个 JavaScript 对象,比如说 parentObj

How can I improve the below code. I have a reduce, a map and a double for loop.

[
{
NAME: 'SOMENAME',
ID: '1',
FROM: '20191223',
TO: '99991231'
},

{
NAME: 'SOMENAME',
ID: '2',
FROM: '20191223',
TO: '99991231'
},

{
NAME: 'SOMENAME',
ID: '3',
FROM: '20191223',
TO: '99991231'
}
]

我创建了一个新对象。

  const newObj = .reduce(
function (obj, item) {
obj[item.NAME] = obj[item.NAME] || [];
obj[item.NAME].push(item.ID);
return obj;
},
{}
);

然后从中取出一个新的对象数组。

  const newObjArr = Object.keys(newObj ).map(function (key) {
return { NAME: key, ID: newObj [key] };
});

然后是一个双 for 循环。

      for (let item1 of newObjArr) {
for (let item2 of parentObj) {
if (item1.NAME=== item2.NAME) {
finalObjArr.push({ NAME: item1.NAME, ID: item1.ID, FROM: item2.FROM, TO: item2.TO});
}
}
}

我的最终输出:

[
{
NAME: 'SOMENAME',
ID: [1, 2, 3],
FROM: '20191223',
TO: '99991231'
},
...
]

最佳答案

您已经拥有了 newObj,您可以在其中按名称查找内容。无需构建 newObjArr 并循环遍历它以按名称搜索。就这么写

for (const item2 of parentObj) {
const item1_NAME = item2.NAME;
const item1_IDs = newObj[item1_NAME];
finalObjArr.push({ NAME: item1_NAME, ID: item1_IDs, FROM: item2.FROM, TO: item2.TO});
}
<小时/>

鉴于您在评论中的更新,我建议您实际上将包含所有信息的对象放入 newObj 中,然后您需要获取的只是其作为数组的值:

const newObj = parentObj.reduce((obj, item) => {
if (!(item.NAME in obj))
obj[item.NAME] = { NAME: item.NAME, ID: [], FROM: item.FROM, TO: item.TO };
obj[item.NAME].ID.push(item.ID);
return obj;
}, {});
const finalObjArr = Object.values(newObj);

关于javascript - 重构 map、reduce 和 double for 循环 - javascript es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868573/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com