如何将属性值转换为键?

时间:2018-11-19 06:31:02

标签: javascript jquery json

我有一个JSON格式。

view

我想将其转换为以下格式的对象:

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

我想要这样做的原因是,我可以轻松获取myObj.NY值。

6 个答案:

答案 0 :(得分:1)

简短

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以像下面一样尝试使用“ Object.assign”和“ Array.map”来获得所需的结果

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)

答案 3 :(得分:0)

您可以对该数组执行简单的forEach()循环,并进行数组解构,以使您的代码简短明了。

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

答案 4 :(得分:0)

使用Array.prototype.reduce()

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

答案 5 :(得分:0)

这也可以使用map来实现,方法是通过[key]语法分配对象密钥:

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

请参阅https://jsfiddle.net/gL6bcqm1/1/