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.

Melissa94
  • 413
  • 1
  • 5
  • 12
  • 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(). – dandavis Oct 02 '18 at 03:48
  • The first piece of code is only an object, not an array of objects. – Adam Oct 02 '18 at 03:48
  • @dandavis updated my question – Melissa94 Oct 02 '18 at 03: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. – Phil Oct 02 '18 at 03:54

2 Answers2

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)
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • 1
    Seems kinda odd to recreate the accumulator each iteration when you could just use `return accum[key] = '+ ' + value, accum` – Phil Oct 02 '18 at 03:53
  • @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. – JLRishe Oct 02 '18 at 03:56
  • 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 Oct 02 '18 at 03:57
  • 1
    @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. – JLRishe Oct 02 '18 at 03:58
  • @Melissa94:  [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Oct 02 '18 at 21:32
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 )
Phil
  • 157,677
  • 23
  • 242
  • 245
You Nguyen
  • 9,961
  • 4
  • 26
  • 52