0

I have an array below,

var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}

but I want to transform it into

var array2 = 
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}

Is this possible?

0

3 Answers 3

2

This should do it:

// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
   // Note that array.Id = [1,2,3] does not result in corresponding keys
   // array.Id[0] corresponds to value 1!
   array2.data.push({
       Id: array.Id[i],
       Name: array.Name[i],
       Row: array.Row[i]
   });
}
Sign up to request clarification or add additional context in comments.

Comments

1
var array2 = {data: []};
for (i in array.Id) {
    array2.data.push({
        Id: array.Id[i],
        Name: array.Name[i],
        row: array.row[i]
    });
}

Didn't test it

1 Comment

No, it's not. array[i] is meaningless here
0

it's not an array. it's an object.

var myArr = [1,2,3]; //Array definition


var myObj = {test:"1",test2:"2"}; //Object Definition



var array = [1,[1,2,3]]; // multidimensional array 

6 Comments

but,actually,object is a multidimensional array too?
no they are not. I've added multidimensional array example. arrays are different from objects.
Arrays in Javascript are a specific type of object, with auto-incrementing numbers for keys. You're using objects, but not arrays.
Pretty much everything in JavaScript is technically an object, including arrays. Still, it is pretty clear what the OP wants to do and this answer is not really an answer.
yes I know that this isn't an answer, but I wanted the author to know that arrays are not normal objects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.