如何更改JSON的结构

时间:2017-03-30 10:25:47

标签: javascript html angularjs arrays json

我有像这样的JSON

{"a":1,"b":2,"c":3}

我怎样才能像这样转换它的结构

[{
"option_id": "a",
"option_value": "1"
},
{
"option_id": "b",
"option_value": "2"
},
{
"option_id": "c",
"option_value": "3"
}]

我尝试了JSON.stringifyresult.push([i,data[i]])等但到目前为止没有成功

5 个答案:

答案 0 :(得分:3)

使用Array#reduce



var json = {"a":1,"b":2,"c":3},
    result = Object.keys(json).reduce(function(s,a){
      s.push({ "option_id": a, "option_value": json[a] });
      return s;
    }, []);
    
    console.log(result);




答案 1 :(得分:3)

您必须使用map函数,该函数接受回调函数。

此外,您应该使用Object.keys()方法来获取对象的keys

var object={"a":1,"b":2,"c":3}
console.log(Object.keys(object).map(function(item){
    return {"option_id": item,"option_value":object[item]};
}));

答案 2 :(得分:0)

如果您使用ECMAScript 5.1或更新版本(或合适的polyfill),则以下内容将按照您的要求进行

let value = {"a":1,"b":2,"c":3};
let newValue = Object.keys(value).map(key => ({option_id:key,option_value:a[value]}));

答案 3 :(得分:0)

//with old syntax   
q = {"a":1,"b":2,"c":3}
arr = []
for(i in q) {
  arr.push({'object_id': i, 'object_value': q[i] });
}

答案 4 :(得分:0)

var object = {"a":1, "b":2, "c":3}, resultArr = [];

for(var key in object) {
resultArr.push({
"option_id": key,
"option_value": object[key]
});
}

console.log(resultArr);

var outputArr = Object.keys(object).map(function(eachItem){
return {
"option_id": eachItem,
"option_value": object[eachItem]
};
});

console.log(outputArr);