2

I am new to javascript. I tried to achieve this output in array but I really cannot do it.

Output should be:

["test", "test1"],
["test2", "test3"]

From this:

The data from items:

items = [
    {
       data1: "test",
       data2: "test1"
    },
    {
       data1: "test2",
       data2: "test3"
    },
]

I tried to push to a new array in here but not working. Is there any workaround here?

  for (var i = 0; i < items.length; i++) {
      items[i]
  }
1
  • Your loop doesn't do anything. Can you post what you have actualy tried? Commented Nov 4, 2016 at 8:08

3 Answers 3

2

Use Array#map method

var items = [{
  data1: "test",
  data2: "test1"
}, {
  data1: "test2",
  data2: "test3"
}, ];

console.log(
  items.map(function(obj) {
    return [obj.data1, obj.data2]
  })
);

Sign up to request clarification or add additional context in comments.

Comments

1

A solution using Array.prototype.reduce and listing out all the values from items into an array and not just data1 and data2:

var items=[{data1:"test",data2:"test1"},{data1:"test2",data2:"test3"}];

var result = items.reduce(function(prev,curr){
  prev.push(Object.keys(curr).map(e=>curr[e]));
  return prev;
},[]);

console.log(result);

Comments

0

Here is another solution for you :

jsfiddle

var items= [
   {
     data1: "test",
     data2: "test1"
   },
   {
     data1: "test2",
     data2: "test3"
   },
];
for(i in items){
   array=[];
   for(j in items[i]){
      array.push(items[i][j])
   }
   console.log(array);
}

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.