I want to covert this javascript Array
[ "Data", [ "API", "Apiales", "Apiaceae", "Apia", ] ]
to this rearranged json Format
[ {"name":"API","id":"1"}, {"name":"Apiales","id":"1"}, {"name":"Apiaceae","id":"1"}, {"name":"Apia","id":"1"} ]
Thanks
update: i have tried this
var aNewData =[];
for(i in aData[1]){
var item={};
item.name = aData[1][i];
item.id = "1";
aNewData[i]=item;
}
Where do the ids come from? Test following script, your array is in aData
and the result will be in aNewData
:
var aNewData = [];
for (var i = 0; i < aData[1].length; i++) {
aNewData.push({
"name": aData[1][i],
"id": 20 + i
});
}
Also see this example .
You might easily transform those data via folding:
var sourceData = ["API","Apiales","Apiaceae","Apia"];
var transformed = sourceData.reduce(function(result, name, index) {
return result.concat({
name: name,
id: 20 + index
});
}, []);
This will give you essentially the same, as the for loop of scessor, but in a more data-centric way.
Think of it like this:
You hold your source data (the array with all those "api*" strings)
You create a fresh resulting array []
(passed as 2nd argument to the reduce
), which should be returned as your next result.
Pass an unnamed function to reduce
that will be called with 3 arguments, each time it is called, namely result
, which is you recently created array, name
the value of each of those "api*" strings, and index
, which is the index of those strings within the original array.
You look at each of those "api*" strings consecutively and put a new object containing your desired data into it. As result.concat
will return the whole array, you just add those
The result
array containing all your data will be returned.
But just in case you wanted to be backward compatible with older browsers, I'd recommend using underscore.js for that.
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.