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]
 }
asked Nov 4, 2016 at 8:06
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]
 })
);

answered Nov 4, 2016 at 8:09
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);

answered Nov 4, 2016 at 8:12

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);
}
answered Nov 4, 2016 at 8:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.