【问题标题】:How to combine an array of objects into one object and if the value is different then change the value to 'Multiple'?如何将一组对象组合成一个对象,如果值不同则将值更改为“多个”?
【发布时间】:2023-01-12 04:09:43
【问题描述】:

我想将它们合二为一,但如果属性的值不同,我想改写“多个”。与在 Mac 上的 Pages 文稿中的文本编辑器中一样。

const myObj = [{
  color: 'Blue',
  font: 'Arial'
},
{
  color: 'Green',
  font: 'Arial'
},
{
  color: 'Blue',
  font: 'Arial'
},]

成为:


const results = {
color: 'Multiple',
font: 'Arial'
}

const results = arrObj.reduce(function(result, currentObject) {
    for (var key in currentObject) {
        if (currentObject.hasOwnProperty(key)) {
            result[key] = currentObject[key]; 
        }
    }
    return result;
}, {});

结果是:

{ 颜色:'蓝色', 字体:'宋体' }

【问题讨论】:

    标签: javascript


    【解决方案1】:

    我不知道在这种情况下我是否会使用reduce()。增量构建结果对象可以让您轻松跟踪已经遇到的值:

    const myObj = [{
        color: 'Blue',
        font: 'Arial'
      },
      {
        color: 'Green',
        font: 'Arial'
      },
      {
        color: 'Blue',
        font: 'Arial'
      }
    ];
    
    function combine(objArray) {
      let result = {};
    
      for (const obj of objArray) {
        for (const [key, val] of Object.entries(obj)) {
            if (key in result && result[key] !== val) {
              result[key] = "Multiple";
            } else {
              result[key] = val;
            }
          }
        }
    
        return result;
      }
    
      console.log(combine(myObj));

    【讨论】:

      【解决方案2】:

      只是@Brandon 的端口使用reduce

      function combine(objArray) {
        return objArray.reduce((result, obj) => {
            for (const [key, val] of Object.entries(obj))
                if (key in result && result[key] !== val)
                    result[key] = "Multiple";
                else
                    result[key] = val;
            return result;
        }, {});
      }
      
      console.log(combine([{
        color: 'Blue',
        font: 'Arial'
      },
      {
        color: 'Green',
        font: 'Arial'
      },
      {
        color: 'Blue',
        font: 'Arial'
      }]));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        • 2014-10-30
        • 1970-01-01
        • 2021-04-24
        相关资源
        最近更新 更多