牛魔王的故事
2021-06-27 17:54:52
我有這個數組const array = [1, 3, 6];和這個對象const obj = { 1: {id: 1, foo: 'a', ...}, 2: {id: 2, foo: 'b', ...} 3: {id: 3, foo: 'c', ...}, 4: {id: 4, foo: 'd', ...}, 5: {...}, 6: {...} ... // up to 1000 key/value paris};我想知道如何obj使用array. 一種方法是obj.filter(elem => elem.id...);但這會遍歷 中的所有元素obj,即使array. 更好的是迭代array,但是array.filter(elem => elem === obj.id ...);然后只返回array(意思是,1, 3, 6)中的元素。我需要的是一個看起來像的數組const result = ['s', 'b', 'c', 'd'];做這個的最好方式是什么?
3 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
如果您有idas 鍵,則可以通過過濾鍵以僅獲取已知鍵然后映射值來映射所需的值。
const
array = [1, 3, 6],
object = { 1: { id: 1, foo: 'bar' }, 2: {}, 3: { id: 3, foo: 'foo' }, 4: {}, 5: {} },
result = array
.filter(Object.hasOwnProperty.bind(object))
.map(id => object[id].foo);
console.log(result);

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
如果中的所有值都array存在,obj則使用Array.map否則如果缺少條目,obj則可以使用Array.reduce
const array = [1, 3, 6];
const obj = {1: {id: 1, foo: 'bar'},2: {id: 2, foo: 'foo'}};
const result = array.reduce((a,c) => obj[c] ? a.concat(obj[c].foo) : a, []);;
console.log(result);
添加回答
舉報
0/150
提交
取消