0

I have array of the following form:

[
{key: "key1", value: value1}
{key: "key2", value: value2}
{key: "key3", value: value3}
...
]

I need to convert to the following form:

{ { key1 : value1},  { key2 : value2},  { key3 : value3} } 

How to do it with reduce() ?

I am trying to use this code:

 var someObject = this.someArray.reduce(function(acc, item) {
            return { [item.key]: item.value};
        }, {});

but I always get only the last item instead of all of them.

8
  • All of your keys are the same key. Also using + on objects coerces them to strings "[object Object]". It's unclear how you thought that might work. Commented May 11, 2020 at 13:26
  • 1
    Your expected output is invalid. Do you want an array of objects? Commented May 11, 2020 at 13:27
  • @jonrsharpe- I fixed the input keys Commented May 11, 2020 at 13:28
  • Give a minimal reproducible example. Adding commas and quotes to make it minimally valid syntax, this doesn't output only the last item, it outputs "[object Object][object Object][object Object][object Object]". Commented May 11, 2020 at 13:29
  • 1
    @Dane Brouwer- so sorry again - I edited the above example to the line that gave me only the last item. Commented May 11, 2020 at 13:32

2 Answers 2

2

The issue is in your return

return acc + { [item.key]: item.value};

You cannot use the + operator to add objects. Try the following:

acc[item.key] = item.value;
return acc

This assumes your keys are all unique. See full example below:

let x = [{
    key: "key1",
    value: 'value1'
  },
  {
    key: "key2",
    value: 'value2'
  },
  {
    key: "key3",
    value: 'value3'
  },
].reduce((accumulatedValue, curentValue) => {
  accumulatedValue[curentValue.key] = curentValue.value;
  return accumulatedValue
}, {})
console.log(x);

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

4 Comments

When I try this I get error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
@codeKnight Well it can't be an issue with the change I suggested. There is likely an issue elsewhere. Can you post more of your code?
I'm marking this answer as the answer - but - in order to get rid of the error that I got in the comment here above - I had to add an explicit type - so I'm going to edit this answer with that.
I don't have enough reputation so the edit part won't show until it is approved - so I write here: I added: {} as Record<string, string> at the end ....
1

Either you seek an array of object, then the following example applies :

const res = [{
  key: 'key1',
  value: 'value1',
}, {
  key: 'key1',
  value: 'value1',
}, {
  key: 'key1',
  value: 'value1',
}].reduce((tmp, {
  key,
  value,
}) => [
  ...tmp,

  {
    [key]: value,
  },
], []);

console.log(res);


Either you seek an unique object, then the following example applies :

const res = [{
  key: 'key1',
  value: 'value1',
}, {
  key: 'key2',
  value: 'value2',
}, {
  key: 'key3',
  value: 'value3',
}].reduce((tmp, {
  key,
  value,
}) => ({
  ...tmp,

  [key]: value,
}), {});

console.log(res);


About your code, as people told you already in the comments, you cannot simply use the + operator to concatenate either arrays or objects.

3 Comments

I removed the + from the code in question. it was a mistake. look now.
can you clarify your second answer ? what is the `...tmp' ?
The ... is called the spread operator, what I do is creating a new array composed of all the elements from the accumulator plus a new element. It have the same result as using assignation (like Dane Brouwer answer). here is some tutorial

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.