1

I have list of objects

[
    { regionName:'Alabama',code:'AL', value: 89 },
    { regionName:'Alaska',code:'AK', value: 112 },
    { regionName:'Arizona',code:'AZ', value: 101 },
    { regionName:'Arkansas',code:'AR', value: 123 }
]

which I want to convert to below format -

{
     AL: { value: 89  },
     AK: { value: 112 },
     AZ: { value: 101 },
     AR: { value: 123 }
}

How this can be achieved in JS?

1
  • Just out of curiosity, is there a reason for the other object layer? If you are just going to have value, why not just have AL: 89? I'm guessing you will add to it later? Commented Nov 7, 2017 at 16:19

3 Answers 3

5

You can use map method by passing a callback provided function as parameter which is applied for every item from the given array.

let array=[ { regionName:'Alabama',code:'AL', value: 89 }, { regionName:'Alaska',code:'AK', value: 112 }, { regionName:'Arizona',code:'AZ', value: 101 }, { regionName:'Arkansas',code:'AR', value: 123 } ];

array = Object.assign(...array.map(({ code, value }) => ({ [code]: {value:value }})));
console.log(array);

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

1 Comment

Really pretty nice :)
3

You can use array.prototype.reduce so on every iteration you append new key (AL, AK or AZ) into the final result.

const arr = [
  { regionName:'Alabama',code:'AL', value: 89 },
  { regionName:'Alaska',code:'AK', value: 112 },
  { regionName:'Arizona',code:'AZ', value: 101 },
  { regionName:'Arkansas',code:'AR', value: 123 }
]
    
const result = arr.reduce((prev, curr) => {
  return {
    ...prev,
    [curr.code]: { value: curr.value },
  }
}, {})

console.log(result)

Comments

1

May be I am late but this should also work with simple Array.prototype.map()

var array_of_objects = [
    { regionName:'Alabama',code:'AL', value: 89 },
    { regionName:'Alaska',code:'AK', value: 112 },
    { regionName:'Arizona',code:'AZ', value: 101 },
    { regionName:'Arkansas',code:'AR', value: 123 }
];
var required = {};
var result = array_of_objects.map(function(obj){
  return (required[obj.code] = {value:obj.value});
})

console.log(required);

Result:

{
  "AL": {"value": 89},
  "AK": {"value": 112},
  "AZ": {"value": 101},
  "AR": {"value": 123}
}

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.