gpt4 book ai didi

javascript - 可以合并到这个对象中吗? (javascript)

转载 作者:行者123 更新时间:2023-11-30 11:55:22 25 4
gpt4 key购买 nike

是否有可能(如果可以的话如何)合并具有相同值的标签,以便一个标签拥有其所有画廊的数组?

例如,从这个开始:

[{
tag: "Kings",
galleries: [
"2016 Kings Draft Night"
]
}, {
tag: "Draft",
galleries: [
"2016 Kings Draft Night"
]
}, {
tag: "Kings",
galleries: [
"2016-17 Sacramento Kings Uniforms"
]
}]

并以此结束:

[{
tag: "Kings",
galleries: [
"2016 Kings Draft Night", "2016-17 Sacramento Kings Uniforms"
]
}, {
tag: "Draft",
galleries: [
"2016 Kings Draft Night"
]
}]

非常感谢任何帮助。对此感到难过

最佳答案

您可以 filter()concat()现有的 tag galleries,同时删除不需要的。

var result = data.filter(function(item) {
var ref = this[item.tag];
if(!ref) {
return (this[item.tag] = item);
}
ref.galleries = ref.galleries.concat(item.galleries);
}, {});

var data = [{
tag: "Kings",
galleries: [
"2016 Kings Draft Night"
]
}, {
tag: "Draft",
galleries: [
"2016 Kings Draft Night"
]
}, {
tag: "Kings",
galleries: [
"2016-17 Sacramento Kings Uniforms"
]
}];

var result = data.filter(function(item) {
var ref = this[item.tag];
if(!ref) {
return (this[item.tag] = item);
}
ref.galleries = ref.galleries.concat(item.galleries);
}, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

关于javascript - 可以合并到这个对象中吗? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166370/

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