[英]Construct an object from keys in array
例如,如果我們有一個現有的對象
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
}
您可以在此處使用.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));
一種可能的解決方案是使用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));
另一種方法是通過將callback
函數作為參數來使用reduce
方法。
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));
您可以使用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);
您可以使用遞歸。
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));
您可以按如下所示編輯函數,它將為您提供所需的輸出。
function getObjectByKeys(obj, [first, ...rest]) {
if(rest.length > 0 ) return getObjectByKeys(obj[first], rest)
else return obj[first]
}
getObjectByKeys(mainObject, ['topics', 'topic1'])
我會將主題更改為數組,以便查找任何元素變得微不足道。 該代碼現在幾乎可以被人類閱讀:“在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 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.