gpt4 book ai didi

javascript - 如何在 Javascript 中合并和过滤两个对象数组?

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

我有以下内容:

var owners = [{
"ownerid": "11",
"name": "jane",
"sex": "female"
}, {
"ownerid": "22",
"name": "mike",
"sex": "male"
}, {
"ownerid": "33",
"name": "alex",
"sex": "male"
}];

var cars = [{
"ownerid": "11",
"make": "ford",
"model": "mustang"
}, {
"ownerid": "11",
"make": "honda",
"model": "civic"
}, {
"ownerid": "33",
"make": "toyota",
"model": "corolla"
}];

我想以这个结束

var mergedandfiltered = [{
"name": "jane",
"sex": "female",
"make": "ford",
"model": "mustang"
}, {
"name": "jane",
"sex": "female",
"make": "honda",
"model": "civic"
}, {
"name": "alex",
"sex": "male",
"make": "toyota",
"model": "corolla"
}];

这个想法是合并和过滤结果,这样我就有了所有者、所有者属性(property)以及他们拥有的汽车和汽车属性(property)的列表。迈克没有任何汽车,因此不会显示在结果中。 “ownerid”是通用链接,但我不需要它在结果中显示。

请首选纯JS解决方案!

最佳答案

首先构建一个对象以供车主引用,然后迭代汽车,并组合一个新对象。

var owners = [{ "ownerid": "11", "name": "jane", "sex": "female" }, { "ownerid": "22", "name": "mike", "sex": "male" }, { "ownerid": "33", "name": "alex", "sex": "male" }],
cars = [{ "ownerid": "11", "make": "ford", "model": "mustang" }, { "ownerid": "11", "make": "honda", "model": "civic" }, { "ownerid": "33", "make": "toyota", "model": "corolla" }],
obj = {},
result;

owners.forEach(function (a) {
obj[a.ownerid] = a;
});

result = cars.map(function (a) {
return {
name: obj[a.ownerid].name,
sex: obj[a.ownerid].sex,
make: a.make,
model: a.model
};
});

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

关于javascript - 如何在 Javascript 中合并和过滤两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35654170/

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