Home > Mobile >  How to convert an array of objects into a single object using reduce?
How to convert an array of objects into a single object using reduce?

Time:12-01

I have the following array of object.

[
  { claimNumber1: 'R12345', checkNumber1: '' },
  { claimNumber2: 'T1234', checkNumber2: 'abcd' },
  { claimNumber3: 'Z4567', checkNumber3: 'qwer' }
]

Using reduce, I want to convert this to below.

{
    claimNumber1:'R12345',
    checkNumber1:'',
    claimNumber2:'T1234',
    checkNumber2:'',
    claimNumber3:'Z4567',
    checkNumber3:'',

}

I tried below but didn't get what I expected.

.reduce((obj, item) =>{
    return {...obj,item}
} ,{});

CodePudding user response:

You should spread the item object, because item is an object

const arr = [
  { claimNumber1: "R12345", checkNumber1: "" },
  { claimNumber2: "T1234", checkNumber2: "abcd" },
  { claimNumber3: "Z4567", checkNumber3: "qwer" },
];

const result = arr.reduce((obj, item, i) => {
  return { ...obj, ...item, [`checkNumber${i   1}`]: "" };
}, {});

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Almost there. You just need to spread the item as well.

.reduce((obj, item) => {
  return {
    ...obj,
    ...item,
  };
}, {});

CodePudding user response:

I think you should spread every item in reducer. Here is my code.

const res = arr.reduce((prev, item) => {
 return { ...prev, ...item };
}, {});

And result is

{
  claimNumber1: 'R12345',
  checkNumber1: '',
  claimNumber2: 'T1234',
  checkNumber2: 'abcd',
  claimNumber3: 'Z4567',
  checkNumber3: 'qwer'
}

CodePudding user response:

I'm not sure of the benefit of using reduce in this situation. A simple loop would be self-documenting, and easier to read.

const data = [
  { claimNumber1: 'R12345', checkNumber1: '' },
  { claimNumber2: 'T1234', checkNumber2: 'abcd' },
  { claimNumber3: 'Z4567', checkNumber3: 'qwer' }
];

const out = {};

// For every object in the array
for (const obj of data) {

  // Get an array of its keys and iterate over them
  for (const key of Object.keys(obj)) {

    // If it's a claim add that value to the output
    // object property, otherwise set that property value
    // to an empty string.
    if (key.startsWith('claim')) {
      out[key] = obj[key];
    } else {
      out[key] = '';
    }
  }
}

console.log(out);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Related