我怎样才能从
获得data1 = [
{ "label": "Some Label", "value": '018'},
{ "label": "Another Label", "value": '020'}
]
到
data2 = {
"018": "Some Label",
"020": "Another Label"
}
for循环应该怎么样?
for (let item of data){
....
}
答案 0 :(得分:3)
您可以使用reduce()
并返回对象。
var data = [
{ "label": "Some Label", "value": '018'},
{ "label": "Another Label", "value": '020'}
]
var result = data.reduce(function(r, e) {
r[e.value] = e.label;
return r;
}, {})
console.log(result)
答案 1 :(得分:3)
您可以使用Array#forEach
并构建一个值为关键字的对象。
var data1 = [{ label: "Some Label", value: '018'}, { label: "Another Label", value: '020'}],
data2 = {};
data1.forEach(function (a) {
data2[a.value] = a.label;
});
console.log(data2);
答案 2 :(得分:3)
如果你想坚持使用for..of
循环,你可以这样做:
var data2 = {};
for (let item of data) {
data2[item.value] = item.label
}
答案 3 :(得分:1)
试试这个......
var data1 = [{
"label": "Some Label",
"value": '018'
}, {
"label": "Another Label",
"value": '020'
}];
var data2 = {};
for (i = 0; i <= data1.length - 1; i++) {
data2[data1[i].value] = data1[i].label;
}
console.log(data2);
答案 4 :(得分:1)
试试这个,它应该可以正常工作
/** declare data1 */
const data1 = [
{
label: 'Some Label',
value: '018'
},
{
label: 'Another Label',
value: '020'
}
]
/** declare data2 */
const data2 = {}
/** loop data1 to get data2 value */
data1.forEach(item => {
data2[item.value] = item.label
})
console.log(data2)