热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何获取以JavaScript列表形式给出的属性子集?

我需要具有数组的地图对象数据constdata[{name:"John",age:"22"

我需要具有数组的地图对象数据

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)


,

只需遍历keymap

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)



推荐阅读
author-avatar
一剑吹雪_811
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有