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 ```
3 Answers 3
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.
Comments
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)']);
Comments
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)
4 Comments
console.log(obj)
(and to the snippet above) and it looks the same to me in the browser console 0: {YEAR(Scan): '2020' }
- "year(scan)" is greyed and not in quotes. Note, it is not a string, you use ["string"]
to access variables with invalid variable names var YEAR(Scan)=2020
would give an error. Perhaps you could add: console.log(JSON.stringify(obj))
so the original obj can be recreated faithfully.
obj
variable contain?Object.values(obj.jaar)
? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…