2
const ori = {
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa"
}

How do I concate above array of object into

{
    "AL": "+ Alabama",
    "AK": "+ Alaska",
    "AS": "+ American Samoa"
}

using reduce?

I tried

const r = Object.entries(ori).reduce((accum, [key, value], i) => {
    console.log(key)
    accum = {[key]: `+ ${value}`}

    return accum
},{})
console.log(r)

I only got the last iteration value.

4
  • 2
    reduce is for arrays, you'd have to convert it first. also reduce is for many->one, and you want many->many, which is a map(). Commented Oct 2, 2018 at 3:48
  • The first piece of code is only an object, not an array of objects. Commented Oct 2, 2018 at 3:48
  • @dandavis updated my question Commented Oct 2, 2018 at 3:49
  • 1
    The reason your attempt doesn't work is because you assign the accumulator to an entirely new object each iteration. What you want to do is add new properties to the existing accumulator. Commented Oct 2, 2018 at 3:54

2 Answers 2

3

You just need to use the ... operator to combine the current value of accum with the next entry:

const ori = {
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa"
}

const r = Object.entries(ori).reduce((accum, [key, value]) => {
    console.log(key)
    return {...accum, [key]: `+ ${value}`};
},{})
console.log(r)

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

5 Comments

Seems kinda odd to recreate the accumulator each iteration when you could just use return accum[key] = '+ ' + value, accum
@Phil Sure, you could, but part of the idea of functional programming (such as reduce) is avoiding mutability. accum[key] = would mutate the accumulator object. If the number of items is a known commodity and it's small, then the approach above shouldn't be too big of a deal.
Since the accumulator is created new specifically for the reduce operation, I don't think I've ever seen an issue in mutating it
@Phil No, there's no issue in mutating it. It's simply a matter of whether you want to consistently adhere to immutability or not.
1

transform property value of an object

An alternative for using reduce

Try this:

const obj = {
  "AL": "Alabama",
  "AK": "Alaska",
  "AS": "American Samoa"
}
let clone = {}
for (var propt in obj) {
  clone[propt] = `+ ${obj[propt]}`
}
console.log(clone )

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.