gpt4 book ai didi

javascript - 减少函数插入数组值

转载 作者:行者123 更新时间:2023-11-28 03:20:40 24 4
gpt4 key购买 nike

我有对象数组:

const items = [{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00002' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00002' },
{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00003',
asset_code: 'ASSET00004' },
{ search_type: 'scene',
search_code: 'TBA_SCENE00006',
asset_code: 'ASSET00002' },
];

并且想要返回类似的内容:

{
ASSET00002: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002"],
scene:["TBA_SCENE00006"]
},
ASSET00004: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002","TBA_JOB00003"]
},
}

这里我使用Reduce函数来使用这个逻辑:

const result = items.reduce((acc, item) => {
const { search_type, search_code, asset_code } = item;
return {
...acc,
[asset_code]: {
...acc[asset_code], [search_type]: [search_code]
},
};
}, {});

我得到以下结果:

{
ASSET00002: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00002"],
scene:["TBA_SCENE00006"]
},
ASSET00004: {
environment:["TBA_ENVIRONMENT00002"],
job:["TBA_JOB00003"]
},
}

在返回“ASSET00004”->“job”时,我应该得到具有两个值的数组,但只得到一个。我知道我的代码缺少一些内容,但无法找到将值正确插入数组的方法。如有任何帮助,我们将提前感激不尽。

最佳答案

您可以通过单个 reduce 方法来完成此操作,确保在迭代对象时添加到任何现有数组:

const items = [{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00002' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00002' },
{ search_type: 'environment',
search_code: 'TBA_ENVIRONMENT00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00002',
asset_code: 'ASSET00004' },
{ search_type: 'job',
search_code: 'TBA_JOB00003',
asset_code: 'ASSET00004' },
{ search_type: 'scene',
search_code: 'TBA_SCENE00006',
asset_code: 'ASSET00002' },
];

const assets = items.reduce((acc, el) => {
if (!acc[el.asset_code]) {
acc[el.asset_code] = {};
}
acc[el.asset_code][el.search_type] =
[...acc[el.asset_code][el.search_type] || [], el.search_code];
return acc;
}, {});

console.log(assets);

关于javascript - 减少函数插入数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186325/

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