Riya1669
Riya1669

Reputation: 19

How to change array to object in Javascript?

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?

Upvotes: 1

Views: 59

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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

Upvotes: 1

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

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)

Upvotes: 3

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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

Upvotes: 5

Related Questions