Home > Software engineering >  How to turn object with array into array?
How to turn object with array into array?

Time:10-13

I'm trying to turn the values of an array inside an object to a normal array.

Right now I'm doing something like this in my AJAX success function:

var obj = data
              
console.log(obj)

var array = Object.keys(obj)
 .map(function(key) {
   return obj[key];
 });

console.log(array)

This is what I get in my console:

{jaar: Array(2)}
 jaar: Array(2)
  0: YEAR(Scan): "2020"
   [[Prototype]]: Object
  1: YEAR(Scan): "2021"
   [[Prototype]]: Object
  length: 2
  [[Prototype]]: Array(0)
  [[Prototype]]: Object

I want to have something simply as this

["2020", "2021"]

How can I achieve this and what am I doing wrong right now?

console.log(obj) at the start gives this output in the console:

jaar: Array(2)
0: {YEAR(Scan): '2020'}
1: {YEAR(Scan): '2021'}
length: 2
[[Prototype]]: Array(0)
[[Prototype]]: Object ```

CodePudding user response:

If you have a plain object like const obj = { x: 10, y: 20 } and you want to have an array of its values, you can simply use Object.values(obj) that will return you [10, 20].

Seems like your object has more complex structure.

If you know for sure, any value of your object is a value or array, like const obj2 = { x: 10, y: [20, 30, 40], z: [50, 60]} you can flatten it.

Object.values(obj2).flat() will return you [10, 20, 30, 40, 50, 60].

For more complex structures you need to have more complex handlers.

CodePudding user response:

jaar is already an array of objects. You can simply use .map() and get the respective property value from each array element.

let ans =jaar.map(x => x['YEAR(Scan)']);

CodePudding user response:

Other answer provides the must succinct code (using .map) - to make the the smallest change to your existing code, change:

You can read the YEAR(Scan) property like so:

return obj[key]["YEAR(Scan)"];

Updated code:

var obj = 
  [ 
    { "YEAR(Scan)":"2020" },
    { "YEAR(Scan)":"2021" }
  ]
  

console.log(obj)

var array = Object.keys(obj)
 .map(function(key) {
   return obj[key]["YEAR(Scan)"];
 });

console.log(array)

  • Related