1

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;
            }
Jaideep Singh
  • 589
  • 2
  • 8
  • 18

2 Answers2

3

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.

scessor
  • 15,995
  • 4
  • 43
  • 54
  • Thanks scessor,is it Performance wise better than my updated solution? – Jaideep Singh Feb 09 '12 at 09:15
  • You're welcome. There should be no performance difference between our solutions. – scessor Feb 09 '12 at 09:20
  • 1
    @JaideepSingh Using `for...in` to iterate on an array is not a good practice. Use a simple `for` as *scessor* did. [Read more about the reasons for not using `for...in` on SO](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – kapa Feb 09 '12 at 09:20
0

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:

  1. You hold your source data (the array with all those "api*" strings)

  2. You create a fresh resulting array [] (passed as 2nd argument to the reduce), which should be returned as your next result.

  3. 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.

  4. 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

  5. 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.

Tharabas
  • 3,402
  • 1
  • 30
  • 29