0

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}
} ,{});
1
  • 2
    Simply use Object.assign(...arr) Commented Dec 1, 2021 at 5:23

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

take another look at the output the OP requires.
@Andy Edited answer, Thanks for the feedback
0

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

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

1 Comment

How are you differentiating between the keys in this example?
0

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

1 Comment

That's not the output the OP requires.
0

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

Additional documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.