gpt4 book ai didi

javascript - 如何使用数组选择对象数组中的特定键?

转载 作者:行者123 更新时间:2023-12-03 07:52:36 24 4
gpt4 key购买 nike

我有一个像这样的颜色数组

var colors = ['yellow','blue']

我的数据库返回我

var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]

所以我想在另一个数组中仅显示颜色数组(第一个数组)中的颜色这就是我想要的

var newArray = [{name : "Paul", yellow : "it's yellow or not", blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course",blue:"it's light blue"}]

这就是我所做的

    var colors = ['yellow','blue']
var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]

var newArray = db.map(x => {
var selectedColors = colors.map(y => { return { [y]: x[y] } })
return {
name : x.name ,
...selectedColors
}
})

但是我有这样的东西(例如1行):

{
0 : {yellow : "it's yellow or not"},
1 : {blue: "it's darkblue"},
name : "Paul"
}

但我想要这个

{
yellow : "it's yellow or not",
blue: "it's darkblue",
name : "Paul"
}

最佳答案

对于 db 中的每个对象,迭代 colors 并从对象中获取与 colors 当前元素对应的属性:

const db = [/* Your array of objects here */];
const colors = [/* Your array of color names here */];

const newArray = db.map((object) => {
const excerpt = {
name: object.name,
};

for (const color of colors) {
excerpt[color] = object[color];
}

return excerpt;
});

如果您关心行数,可以使用 .reduce 方法代替:

const array = db.map((object) => colors.reduce((excerpt, color) => ({
...excerpt,
[color]: object[color],
}), {
name: object.name,
}));

关于javascript - 如何使用数组选择对象数组中的特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76805945/

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