Home > Software design >  How to combine an array of objects into one object and if the value is different then change the val
How to combine an array of objects into one object and if the value is different then change the val

Time:01-12

I want to combine these into one but if the values of the property is different I want to write 'Multiple' instead. Same as you would in a text editor in Pages on Mac.

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

to be:


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

result is:

{ color: 'Blue', font: 'Arial' }

CodePudding user response:

I don't know if I'd use reduce() in this case. Incrementally building the result object would allow you to easily track values you've already encountered:

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

CodePudding user response:

Just a port of @Brandon's to using 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'
}]));

  • Related