【问题标题】:JavaScript Reduce an array to find match in ObjectJavaScript 减少数组以在 Object 中找到匹配项
【发布时间】:2020-12-12 22:06:19
【问题描述】:

我正在尝试合并数组方法: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 }

我的选择方法:

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 的初始值设定项,因此如果数组的当前值与对象的键匹配,那么它会将键值添加到累加器中,但我从控制台收到一条错误消息,如果表达式无法返回布尔值.

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

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

请指教。

【问题讨论】:

    标签: javascript arrays object methods reduce


    【解决方案1】:

    您必须始终返回累加器。下面是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 }

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        function select(arr, obj) {
            return arr.reduce((acc, curr) => {
                if(obj[curr]) {
                    acc[curr] = obj[curr];
                }
                return acc;
            }, {})
        }
        

        【讨论】:

        • 在你的答案中添加口头解释会很有帮助
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-25
        • 1970-01-01
        相关资源
        最近更新 更多