Home > Back-end >  push values from array of objects into new array
push values from array of objects into new array

Time:09-23

I have data such as

var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];

Now i need output as new

data = [ [1,7],[2,8] ]

My code outputs [1,2,7,8] , i need as [[1,2],[7,8]].

var data = [{
  "2013-01-21": 1,
  "2013-01-22": 7
}, {
  "2014-01-21": 2,
  "2014-01-22": 8
}];

//document.write(data.length)
var result = [];
for (var i = 0; i < data.length;   i) {

  var json = data[i];
  console.log(json)

  for (var prop in json) {

    result.push(json[prop]);
    console.log(json[prop])

    // or myArray.push(json[prop]) or whatever you want
  }

}

$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

CodePudding user response:

You need to create a nested array in the for loop.

But there's a built-in function Object.values() that will get what you want.

var data = [{
  "2013-01-21": 1,
  "2013-01-22": 7
}, {
  "2014-01-21": 2,
  "2014-01-22": 8
}];
var results = data.map(obj => Object.values(obj));
console.log(results);

CodePudding user response:

Object.values() gives you the values in each object. And you need to iterate over an array of objects, so:

var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];



// data = [ [1,7],[2,8] ]


const extracted = data.map( obj => Object.values(obj))

console.log(extracted)

CodePudding user response:

Object.values()

var data = [{
  "2013-01-21": 1,
  "2013-01-22": 7
}, {
  "2014-01-21": 2,
  "2014-01-22": 8
}];

var result = [];
for (var i = 0; i < data.length; i  ) {
  result.push(Object.values(data[i]));
}

$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

CodePudding user response:

From MDN - The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.

This is exactly what you need.

var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];

const arr = data.map(x => Object.values(x));

console.log(arr);

CodePudding user response:

You can get values array by using Object.values() Solution will be like this:

const data = [{ "2013-01-21": 1, "2013-01-22": 7 }, { "2014-01-21": 2, "2014-01-22": 8 }];
const output = data.map(e => Object.values(e) )
console.log(output)

  • Related