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]
}
-
Your loop doesn't do anything. Can you post what you have actualy tried?Felix Kling– Felix Kling2016年11月04日 08:08:22 +00:00Commented Nov 4, 2016 at 8:08
3 Answers 3
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
Pranav C Balan
115k25 gold badges173 silver badges195 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
kukkuz
42.5k6 gold badges65 silver badges103 bronze badges
Comments
Here is another solution for you :
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
Mihai Alexandru-Ionut
48.6k14 gold badges106 silver badges132 bronze badges
Comments
lang-js