作者:一剑吹雪_811 | 来源:互联网 | 2023-09-24 20:30
我需要具有数组的地图对象数据
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",height:"160cm"}
]
感谢您的帮助
您可以map
覆盖每个对象,并使用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","height"]
const res = data.map(o => keys.reduce((a,k) => (a[k] = o[k],a),{}))
console.log(res)
,
只需遍历key
和map
:
const result = data.map(d=> {
let obj = {};
key.forEach(k=>{
obj[k]=d[k];
})
return obj;
});
const data = [
{name:"John",age:"22",weight:"60",height:"180cm"},{name:"Emma",age:"25",weight:"55",height:"160cm"}
]
const key = ["name","height"];
const result = data.map(d=> {
let obj = {};
key.forEach(k=>{
obj[k]=d[k];
})
return obj;
});
console.log(result)