{
dis:{["String1","String2","String3"]},
par:"pony"
}
而且我希望把它變成這樣:
[
{ name: 'String1', value: "pony" },
{ name: 'String2', value: "pony" },
{ name: 'String3', value: "pony" }
]
{
dis:{["String1","String2","String3"]},
par:"pony"
}
而且我希望把它變成這樣:
[
{ name: 'String1', value: "pony" },
{ name: 'String2', value: "pony" },
{ name: 'String3', value: "pony" }
]
如果更改爲有效的JS數據,您可以用reduce()
var obj = {
dis: ["String1", "String2", "String3"],
par: "pony"
}
var result = obj.dis.reduce(function(r, e) {
r.push({name: e, value: obj.par});
return r;
}, []);
console.log(result)
你可以很容易地做到這一點,但要注意你有雙括號(鬍鬚和方括號)。
var
data = {
dis: ["String1","String2","String3"],
par: "pony"
},
result = [];
for (var index in data.dis)
result.push({ name: data.dis[index], value: data.par}
你可以找到小提琴here。
可以使用Array.protoype.map做到這一點:
var obj = {
dis:["String1","String2","String3"],
par:"pony"
};
var arrOfObj = obj.dis.map(function(name) {
return {
name: name,
value: obj.par
}
});
console.log(arrOfObj)
或者lodash的_.map:
var obj = {
dis:["String1","String2","String3"],
par:"pony"
};
var arrOfObj = _.map(obj.dis, function(name) {
return {
name: name,
value: obj.par
}
});
console.log(arrOfObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>