gpt4 book ai didi

javascript - 如何获取 Javascript 中以列表形式给出的属性子集?

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

我需要带有数组的 map 对象数据

const data = [
{name:"John", age:"22", weight:"60", height:"180cm"},
{name:"Emma",age:"25",weight:"55",height:"160cm"}
]

const key = ["name", "weight", "height"]

我需要这样的结果

const result = [
{name:"John", weight:"60", height:"180cm"},
{name:"Emma", weight:"55",height:"160cm"}
]

感谢您的帮助

最佳答案

您可以映射每个对象,并使用Object.fromEntries使用给定的键创建一个新对象:

const data = [
{ name: "John", age: "22", weight: "60", height: "180cm" },
{ name: "Emma", age: "25", weight: "55", height: "160cm" }
]
const keys = ["name", "weight", "height"]

const res = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])))
console.log(res)

使用reduce代替两个循环会更好,尽管可读性较差:

const data = [
{ name: "John", age: "22", weight: "60", height: "180cm" },
{ name: "Emma", age: "25", weight: "55", height: "160cm" }
]
const keys = ["name", "weight", "height"]

const res = data.map(o => keys.reduce((a, k) => (a[k] = o[k], a), {}))
console.log(res)

关于javascript - 如何获取 Javascript 中以列表形式给出的属性子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410304/

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