我的原始数据是标准的json格式,如下所述:
var data = ["chat1", "chat2"]
我想将它转换成不同的格式,如下所示:
var newData = {chat1 : o.chat1, chat2: o.chat2 , mydates : []}
我被我的代码困住了:
var data = ["chat1", "chat2"]
var v = [];
for (var i = 0; i < data.length; i++) {
v.push({
data[i]: o.data[i],
ques: []
})
}
console.log(v)
答案 0 :(得分:0)
一些错误
push
。
o.data[i]
o[data[i]]
即
v[data[i]] = o[data[i]]
<强>最后强>
for (var i = 0; i < data.length; i++)
{
v[data[i]] = o[data[i]]
}
答案 1 :(得分:0)
如果您可以使用ES6
,则应该是:
var data = ["chat1", "chat2"]
var o = { chat1: 'xxx', chat2: 'yyy', other: 'zzz'};
var newData = Object.assign({ mydates : [] }, ...data.map(prop => ({[prop]: o[prop]})));
console.log(newData);
答案 2 :(得分:0)
data[i]
不是有效名称。你想要这样的东西
var data = ["chat1", "chat2"]
var v = [];
for (var i = 0; i < data.length; i+=2) {
v.push({
"ques": []
});
v[v.length - 1][data[i]] = "o." + data[i];
i++
v[v.length - 1][data[i]] = "o." + data[i];
}
console.log(v)
或者,如果你有其他名为o
的东西:
var data = ["chat1", "chat2"], o={"chat1": "something1","chat2":"something2"};
var v = [];
for (var i = 0; i < data.length; i+=2) {
v.push({
"ques": []
});
v[v.length - 1][data[i]] = o[data[i]];
i++
v[v.length - 1][data[i]] = o[data[i]];
}
console.log(v)