简体   繁体   English

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

[英]JavaScript Reduce an array to find match in Object

I am trying to incorporate array method: reduce.我正在尝试合并数组方法:reduce。 Basically, what I am trying to accomplish here is to reduce the array below to an object where anything that matches obj's key value.基本上,我在这里想要完成的是将下面的数组减少到一个对象,其中任何与 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 }

My select method:我的选择方法:

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;
}

I set {} as initializer for arr.reduce as such if current value of array matches key of object then it would add to accumulator the key value, but I am receiving an error message from the console that if expression cannot return boolean.我将 {} 设置为 arr.reduce 的初始值设定项,如果数组的当前值与对象的键匹配,那么它会将键值添加到累加器中,但是我从控制台收到一条错误消息,如果表达式无法返回布尔值。

Here is my attempt using .reduce() :这是我使用.reduce()尝试:

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

Please advise.请指教。

You must always return the accumulator.您必须始终返回累加器。 Here is how to use reduce下面是如何使用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 }

The accumulator should be returned in all the cases.在所有情况下都应返回累加器。 I used an implementation using a filter for your reference:我使用了一个使用过滤器的实现供您参考:

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;
    }, {})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM