-2

I have a JSON in the format.

var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]

I want to transform it in an object of the format:

myObj = {NY:"good",FL:"bad",CA:"decent"}

The reason I want this is so that I can easily grab the myObj.NY value.

Dong
  • 328
  • 1
  • 3
  • 16

6 Answers6

2

Short and simple

var input = [
  {status:"good", state: "NY"},
  {status:"bad", state: "FL"},
  {status:"decent", state: "CA"}
]
var obj = {};
input.forEach(function(k) {
  obj[k.state] = k.status;
});
console.log(obj);
dotconnor
  • 1,736
  • 11
  • 22
1
var myobj = {}; 
Input.forEach(function (i) { myobj[i.status] = i.state;}
1

You can try using "Object.assign" and "Array.map" as well like below to achieve your desired result

var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]

let res = Object.assign(...input.map(({ state, status}) => ({ [state]: status })))

console.log(res)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
0

You can do a simple forEach() loop on that array with array destructuring to make your code short and simple.

var input = [{
    status: "good",
    state: "NY"
  },
  {
    status: "bad",
    state: "FL"
  },
  {
    status: "decent",
    state: "CA"
  }
];
var res = {};
input.forEach(({state, status})=> res[state] = status);
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Using Array.prototype.reduce()

var myObj = input.reduce( (r,x) => { r[x.status] = x.state ; return r }, {})
Alice Oualouest
  • 836
  • 12
  • 20
0

This can be accomplished as well using map, by assigning the object key through the [key] syntax:

var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
var myObj = Object.assign({}, ...input.map(item => ({
    [item.state]: item.status
})));
console.log(myObj);

see https://jsfiddle.net/gL6bcqm1/1/

briosheje
  • 7,356
  • 2
  • 32
  • 54