JavaScript 减少数组以在对象中查找匹配项

JavaScript Reduce an array to find match in Object

我正在尝试合并数组方法:reduce。 基本上,我在这里想要完成的是将下面的数组缩减为一个对象,其中任何与 obj 的键值匹配的对象。

const arr = ['a', 'c', 'e'];
const obj = { a: 1, b: 2, c: 3, d: 4 };

let output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

我的select方法:

function select(arr, obj) {
  let newObj = {};
  for (let prop in obj) {
    for (let i = 0; i < arr.length; i++) {
      if (prop === arr[i]) {
        newObj[prop] = obj[prop];
      }
    }
  }
  return newObj;
}

我将 {} 设置为 arr.reduce 的初始值设定项,如果数组的当前值与对象的键匹配,那么它会将键值添加到累加器,但我从控制台收到一条错误消息,如果表达式不能 return 布尔值。

这是我尝试使用 .reduce():

function select(arr, obj) {
  let result = arr.reduce(function(x, y) {
    if (y in obj) {
      x[y] = obj[y]
      return x;
    }
  }, {}) 
  return result;
}

请指教

您必须始终 return 累加器。下面是如何使用 reduce

function select(arr, obj) {
    return arr.reduce(function (acc, key) {
        if (key in obj) acc[key] = obj[key];
        return acc;
    }, {});
}

const arr = ['a', 'c', 'e'];
const obj = { a: 1, b: 2, c: 3, d: 4 };

let output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }

在所有情况下都应返回累加器。 我使用了一个使用过滤器的实现供您参考:

const arr = ['a', 'c', 'e'];
const obj = { a: 1, b: 2, c: 3, d: 4 };

function select (obj,arr){
    let newObj = Object.keys(obj).filter(key => arr.includes(key)).reduce((acc,key) => {
                    acc[key]=obj[key]
                    return acc 
                },{})
    return newObj
}
console.log(select(obj,arr)); 

function select(arr, obj) {
    return arr.reduce((acc, curr) => {
        if(obj[curr]) {
            acc[curr] = obj[curr];
        }
        return acc;
    }, {})
}