在转换数据时,obj[i]在javascript中不可迭代



我正试图将数据从一种格式转换为另一种格式,但我得到了错误obj[i] is not iterable为什么我想得到expected output,如下所示的变量

const data = {
"GENERAL": {
"value": null,
"type": "LABEL",
},
"Mobile NUMBER": {
"value": "04061511",
"type": "FIELD",
},
"Abc NUMBER": {
"value": "89999",
"type": "FIELD",
},
"Personal Info": {
"value": null,
"type": "LABEL",
},
"Address": {
"value": "g-78",
"type": "FIELD",
}, "local": {
"value": "090099",
"type": "FIELD",
}
}
const obj = {}
for (var i in data) {
const {type} = data[i];
if (type === 'LABEL') {
obj[i] = []
} else {
obj[i] = [...obj[i], data[i]]
}
}
console.log(obj)

const expectedout = {
"GENERAL": [{
"value": "04061511",
"type": "FIELD",
"displaytext": "Mobile NUMBER"
}, {
"value": "89999",
"type": "FIELD",
"displaytext": "Abc NUMBER"
}],
"Personal Info": [{
"value": "g-78",
"type": "FIELD",
"displaytext": "Address"
}, {
"value": "090099",
"type": "FIELD",
"displaytext": "local"
}]
}

有没有更好的方法将我的当前数据转换为预期数据?我是反应中的ES6这是我的代码

https://jsbin.com/sesipuzeni/1/edit?html,js,控制台,输出

更新

var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
VM5628:8 

对象属性似乎没有保证。当你有数字和字符串时,是正确的

但当你总是"字符串"时,它的顺序是一样的

var obj = {
"first":{a:"jjj"},
"yyy":{a:"jjqej"},
"ttt":{a:"jjsqj"},
"ggg":{a:"jjjs"},
"second":{a:"jjcj"}
};
for (var i in obj) { console.log(i); };

问题是,当处理原始对象的下一个元素时,i不再是包含值数组的元素的键。您需要将其保存在另一个变量中。

const data = {
"GENERAL": {
"value": null,
"type": "LABEL",
},
"Mobile NUMBER": {
"value": "04061511",
"type": "FIELD",
},
"Abc NUMBER": {
"value": "89999",
"type": "FIELD",
},
"Personal Info": {
"value": null,
"type": "LABEL",
},
"Address": {
"value": "g-78",
"type": "FIELD",
},
"local": {
"value": "090099",
"type": "FIELD",
}
}
const obj = {};
var lastLabel;
for (var i in data) {
if (data[i].type === 'LABEL') {
obj[i] = []
lastLabel = i;
} else {
data[i].displaytext = i;
obj[lastLabel] = [...obj[lastLabel], data[i]]
}
}
console.log(obj)

注意,整个方法依赖于对象属性保持它们的顺序,这在JavaScript中是不能保证的。但我认为,它恰好适用于大多数现有的实现。

最新更新