例如,如果我们有一个现有对象
const mainObject = {
title: 'some title',
topics: {
topic1: {
path: '',
id: 1
},
topic2: {
path: '',
id: 2
}
}
}
,我有一个函数可以获取包含键的数组 例如
const arrayOfKeys = ['topics', 'topic1'];
function getObjectByKeys(arrayOfKeys) {
// problem is length of the array may change
const myObject = mainObject[arrayOfKeys[0]][arrayOfKeys[1]];
return myObject;
}
函数应返回
{
path: '',
id: 1
}
答案 0 :(得分:1)
您可以在此处使用.reduce
。用主对象初始化累加器,并在其回调的每次迭代中返回与当前键对应的值。
const mainObject = {
title: 'some title',
topics: {
topic1: {
path: '',
id: 1
},
topic2: {
path: '',
id: 2
}
}
}
const arrayOfKeys = ['topics', 'topic1'];
function getObjectByKeys(arrayOfKeys) {
return arrayOfKeys.reduce((a, el, i, arr) => {
return a[el] || {};
}, mainObject);
}
console.log(getObjectByKeys(arrayOfKeys));
答案 1 :(得分:0)
一种可能的解决方案是使用forEach
循环。
const mainObject = { title: 'some title', topics: { topic1: { path: '', id: 1 }, topic2: { path: '', id: 2 } } }
const arrayOfKeys = ['topics', 'topic1'];
function getObjectByKeys(arrayOfKeys) {
let result = Object.assign({}, mainObject);
arrayOfKeys.forEach(function(key){
result = result[key];
});
return result;
}
console.log(getObjectByKeys(arrayOfKeys));
另一种方法是通过传递reduce
函数作为参数来使用callback
方法。
const mainObject = { title: 'some title', topics: { topic1: { path: '', id: 1 }, topic2: { path: '', id: 2 } } }
const arrayOfKeys = ['topics', 'topic1'];
getObjectByKeys = (arrayOfKeys) => {
return arrayOfKeys.reduce((obj, item) => obj[item], mainObject);
}
console.log(getObjectByKeys(arrayOfKeys));
答案 2 :(得分:0)
您可以使用reduce()
const mainObject = {
title: 'some title',
topics: {
topic1: {
path: '',
id: 1
},
topic2: {
path: '',
id: 2
}
}
};
const arrayOfKeys = ['topics', 'topic1'];
var aa= arrayOfKeys.reduce((carry,value,index)=>{
return carry[value];
},mainObject);
console.log(aa);
答案 3 :(得分:0)
您可以使用递归。
const mainObject = {
title: 'some title',
topics: {
topic1: {
path: '',
id: 1
},
topic2: {
path: '',
id: 2
},
topic3: {
path: 'more depth',
subtopic: {
path: '',
id: 4
},
id: 3
}
}
}
const arrayOfKeys = ['topics', 'topic3', 'subtopic'];
function getObjectByKeys(arrayOfKeys, currentObj, index = 0) {
if(index >= arrayOfKeys.length) {
return currentObj;
}
return getObjectByKeys(arrayOfKeys, currentObj[arrayOfKeys[index]], index+1)
}
console.log(getObjectByKeys(arrayOfKeys, mainObject));
答案 4 :(得分:0)
您可以按如下所示编辑函数,它将为您提供所需的输出。
function getObjectByKeys(obj, [first, ...rest]) {
if(rest.length > 0 ) return getObjectByKeys(obj[first], rest)
else return obj[first]
}
getObjectByKeys(mainObject, ['topics', 'topic1'])
答案 5 :(得分:0)
我会将主题更改为数组,因此查找任何元素变得微不足道。 该代码现在几乎可以被人类阅读:“在mainObject的field_name中找到ID为1的条目。”
const mainObject = {
title: 'some title',
topics: [
{ id: 1, path: 'first' },
{ id: 2, path: 'second' }
]
};
const field_name = 'topics';
const entry_to_find = 1;
const entry = mainObject[ field_name ].find( entry => entry.id === entry_to_find );
console.log( entry );