简体   繁体   中英

Transform JSON data into different format

I have my original data is in the standard json format as mentioned below:

var data = ["chat1", "chat2"]

and i want it to be transformed into different format as below:

var newData = {chat1 : o.chat1, chat2: o.chat2 , mydates : []}

I am stuck with my codes :

 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) 

A couple of mistakes

  • Instead of push , you need to assign the property to an object
  • Instead of o.data[i] , you need to use o[data[i]]

ie

v[data[i]] = o[data[i]]

Finally

for (var i = 0; i < data.length; i++) 
{
    v[data[i]] = o[data[i]]
}

If you can use ES6 , it should be:

 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); 

data[i] is not a valid name. You want something like this

 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) 

OR if you have something else called 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM