问题描述
给定以下对象,我如何遍历此对象以获取键和值,但仅获取以下键:
"myName": "Demo"
"active": "Y"
"myCode": "123456789"
"myType": 1
let a = {
"values": {
"myName": "Demo","active": "Y","myCode": "123456789","myType": 1,"myGroups": [
{
"myGroupName": "Group 1","myTypes": [
{
"myTypeName": "323232","myTypeId": "1"
}
]
},{
"myGroupName": "Group 2","myTypes": [
{
"myTypeName": "523232","myTypeId": "2"
}
]
}
]
}
}
我试过了:
for (const [key,value] of Object.entries(a.values)) {
console.log(`${key}: ${value}`);
For}
但这将返回所有键及其值。
解决方法
您可以使用字典(数组)来包含要为其提取属性的键,然后使用 reduce
对值进行 Object.entries
以生成仅与这些条目匹配的新对象 {{ 3}} 在字典中。
let a = {
"values": {
"myName": "Demo","active": "Y","myCode": "123456789","myType": 1,"myGroups": [{
"myGroupName": "Group 1","myTypes": [{
"myTypeName": "323232","myTypeId": "1"
}]
},{
"myGroupName": "Group 2","myTypes": [{
"myTypeName": "523232","myTypeId": "2"
}]
}
]
}
}
const arr = [ 'myName','active','myCode','myType' ];
const out = Object.entries(a.values).reduce((acc,[key,value]) => {
if (arr.includes(key)) acc[key] = value;
return acc;
},{});
console.log(out);
最好的答案是设置所需键的数组,然后迭代那个数组而不是原始对象条目的数组。这就是您实现这一目标的方式:
let a = {
values: {
myName: "Demo",active: "Y",myCode: "123456789",myType: 1,myGroups: [{
myGroupName: "Group 1",myTypes: [{
myTypeName: "323232",myTypeId: "1"
}]
},{
myGroupName: "Group 2",myTypes: [{
myTypeName: "523232",myTypeId: "2"
}]
}]
}
};
const keys = ['myName','myType'];
const cherryPick = (obj,keys) => keys.reduce((a,c) => (a[c] = obj[c],a),{});
console.log(cherryPick(a.values,keys));
以上示例适用于许多提供的密钥。如果提供的对象中不存在键,则其值将是未定义的。如果您只想保留有值的属性,只需向 cherryPick()
函数添加一个可选过滤器,如下所示:
let test = {
a: 1,b: 2
};
const keys = ['a','b','c'];
const cherryPick = (obj,keys,filter = 0) => keys.filter(key => filter ? obj[key] : 1).reduce((acc,key) => (acc[key] = obj[key],acc),{});
console.log('STORE undefined :: cherryPick(test,keys)',cherryPick(test,keys));
console.log('FILTER undefined :: cherryPick(test,1)',true));
/* Ignore this */ .as-console-wrapper { min-height: 100%; }