如何获取密钥然后删除未关联到数组的密钥? [复制]
Posted
技术标签:
【中文标题】如何获取密钥然后删除未关联到数组的密钥? [复制]【英文标题】:How to get the keys and then remove the keys not associated to an array? [duplicate] 【发布时间】:2021-05-19 04:22:03 【问题描述】:我想获取项目的值,然后删除与列无关的键
下面是我的代码
var columns =['title','code','notes','value','daysCode'];
var items =[
title:'Marvel',
code:'marvel-01',
notes:'spider-man',
value:'Value 2',
daysCode:'Sept 1, 2020',
daysAge:'Nov 1 , 2019',
name:'Peter Parker',
other:'comic'
,
title:'DC',
code:'dc-01',
notes:'batman',
value:'Value 1',
daysCode:'Sept 1, 2020',
daysAge:'Nov 1 , 2019',
name:'Bruce Wayne',
other:'comics'
,
title:'Image',
code:'image-02',
notes:'spawn',
value:'Value 3',
daysCode:'Sept 1, 2020',
daysAge:'Nov 1 , 2019',
name:'Albert Simmons',
other:'comics'
]
输出:
newItems = [
title:'Marvel',
code:'marvel-01',
notes:'spider-man',
value:'Value 2',
daysCode:'Sept 1, 2020'
,
title:'DC',
code:'dc-01',
notes:'batman',
value:'Value 1',
daysCode:'Sept 1, 2020'
,
title:'Image',
code:'image-02',
notes:'spawn',
value:'Value 3',
daysCode:'Sept 1, 2020'
]
我该怎么做?
【问题讨论】:
或ecmascript 6 - Filter object properties by key in ES6 - Stack Overflow 你的问题有点不清楚。您应该发布您到目前为止编写的代码,以便网站用户可以看到您正在尝试做什么以及哪里出了问题。 @user202729 在这种情况下,您将问题标记为欺骗 @AnuragSrivastava 我知道这一点。但是由于不止一个,我只是在检查哪个更好等等......(除了我只有一个标志) 简单而简短的答案是 - const result = items.map(item => return ((title,code,notes,value,daysCode) => (title,code, notes,value,daysCode))(item) ) console.log("result----",result) 【参考方案1】:使用map
和Object.fromEntries
来获得预期的输出:
var columns =['title','code','notes','value','daysCode'];
var items =[ title:'Marvel', code:'marvel-01', notes:'spider-man', value:'Value 2', daysCode:'Sept 1, 2020', daysAge:'Nov 1 , 2019', name:'Peter Parker', other:'comic' , title:'DC', code:'dc-01', notes:'batman', value:'Value 1', daysCode:'Sept 1, 2020', daysAge:'Nov 1 , 2019', name:'Bruce Wayne', other:'comics' , title:'Image', code:'image-02', notes:'spawn', value:'Value 3', daysCode:'Sept 1, 2020', daysAge:'Nov 1 , 2019', name:'Albert Simmons', other:'comics' ]
var newItems = items.map(o=>Object.fromEntries(columns.map(n=>[n,o[n]])));
// using reduce method:
var newItems1 = items.map(o=>columns.reduce((a,e)=>(...a, [e]:o[e]),));
console.log(newItems);
console.log(newItems1);
【讨论】:
有没有办法不使用 Object.fromEntries? @thePeculiarCoder 是的,然后使用reduce
@thePeculiarCoder 请检查更新的副本。您可以使用 reduce 来创建每个对象的子集***.com/a/32184094/3082296
@thePeculiarCoder 如果您有特定要求,您应该在问题中指定。以上是关于如何获取密钥然后删除未关联到数组的密钥? [复制]的主要内容,如果未能解决你的问题,请参考以下文章