0

I have the following array

var a = ["Banana/hgd/kjjkds", "Orange/kldj/kdl", 
         "Apple/jlds/ldks", "Mango/dsfj/dskj"]

Now I want to re-create it as below and make the output

{
    "a1" : "Banana",
    "a2" : "hgd",
    "a3" : "kjjkds"
}
{
    "a1" : "Orange",
    "a2" : "kldj",
    "a3" : "kdl"
}
{
    "a1" : "Apple",
    "a2" : "jlds",
    "a3" : "ldks"
}
{
    "a1" : "Mango",
    "a2" : "dsfj",
    "a3" : "dskj"
}

I tried the following method but without any success:

var b = [];
for (var i = 0; i< a.length; i++) {
    b['a1'] = a[i].split("/")[0];
    b['a2'] = a[i].split("/")[1];
    b['a3'] = a[i].split("/")[2];
    console.log(b);
    b.push(b);
}

The console prints all the array created but the array b only shows the last one. How can i get it to work? Please help.

2
  • 6
    You "below" is object notation and not array. Commented Aug 27, 2012 at 15:57
  • If you have the statement b.push(b); in your code, then you should already know that something is not right. You are adding the array to itself... Commented Aug 27, 2012 at 16:09

2 Answers 2

5

try this:

var spl, b = [];
for (var i = 0, len = a.length; i < len; i++) {

    spl  = a[i].split("/"); /* execute split() just once */

    b[i] = {
      'a1': spl[0],
      'a2': spl[1],
      'a3': spl[2]
    }
}
console.log(b);
Sign up to request clarification or add additional context in comments.

Comments

0

You are pushing the array onto itself. That should set off warning signals.

Instead, you need an output array, and a temporary array to add the keys to.

var b = [], t, s, l = a.length, i;
for( i=0; i<l; i++) {
    s = a[i].split("/");
    t = {
      "a1":s[0],
      "a2":s[1],
      "a3":s[2]
    }
    b.push(t);
}

I've also added a couple of optimisations in there.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.