这很简单。我有这个:
[{"key":"jim","values":{"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
我希望如此:
[{ "key": 'jim', count: 2, total: 79 },
{ "key": 'carl', count: 1, total: 120},
{ "key": 'stacy', count:3, total: 90}];
我已经阅读了有关嵌套对象的内容,以及使用Javascript进行的其他类型的数据操作,但我无法解决我的问题。我想我需要使用.map
方法,但我不能使它工作。感谢。
答案 0 :(得分:1)
试试这个伙伴吧!正如你所说,你是初学者,我做了一步一步的基本循环,请完成代码。 此代码适用于动态一级嵌套对象。
var arr = [{"key":"jim","values":{"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var currentObj = arr[i];
var Obj = {}; // Temporary object
for (var key in currentObj) {
if (typeof currentObj[key] === 'object') { // If it is nested object
for (var deepkey in currentObj[key]) { // Loop again
Obj[deepkey] = currentObj[key][deepkey];
}
}
else {
Obj[key] = currentObj[key];
}
}
newArr.push(Obj);
}
console.log(newArr); // [{ "key": 'jim', count: 2, total: 79 },
{ "key": 'carl', count: 1, total: 120},
{ "key": 'stacy', count:3, total: 90}];
将适用于不同的输入
var arr = [{"key":"jim", "hey": {"ting": "bing"} ,"values": {"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
动态一级嵌套对象
答案 1 :(得分:0)
使用for循环创建一个具有所需格式的新数组。
var initial = [{"key":"jim","values":{"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}];
var target = [];
var obj = {};
for(var i = 0; i< initial.length; i++) {
obj = {"key": initial[i].key, count: initial[i].values.count, total: initial[i].values.total};
target.push(obj);
}
console.log(target);
答案 2 :(得分:-1)
确定。我终于找到了一些对我来说更简单的东西:
else