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

0

6 Answers 6

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

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

Comments

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)

Comments

1
var myobj = {}; 
Input.forEach(function (i) { myobj[i.status] = i.state;}

1 Comment

Input.foreach should be input.forEach
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);

Comments

0

Using Array.prototype.reduce()

var myObj = input.reduce( (r,x) => { r[x.status] = x.state ; return r }, {})

Comments

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/

2 Comments

myObj will be an array of objects, not a single object. Also using Object.assign here is unnecessary.
Wops, sorry, misunderstood the question. Thanks for pointing that!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.