I have an object array created and it's like this:
for(var i =0; i < this.test.length; i ++){
var header = this.test[i].hdr;
var insertData = [];
switch(header){
case 'date':
insertData = {date: "date"};
break;
case 'name':
insertData = {name: "name"};
break;
case 'age':
insertData = {age: "age"};
break;
case 'add':
insertData = {add: "add"};
break;
}
this.hdrtxt.push(insertData);
}
Now, when I try to get the keys of the object, I used this:
Object.keys(this.hdrtxt);
The result is:
(4) ["0", "1", "2", "3"]
But the output I want is this:
(4) ["date", "name", "age", "add"]
I'm sorry I'm just new to this. How can I attain my goal?
tony19
140k23 gold badges281 silver badges354 bronze badges
asked Dec 7, 2018 at 1:42
2 Answers 2
You can use Object.keys
with Object.assign
and spread the data
into one object to get all the keys:
const data = [{ date: "date" }, { name: "name" }, { age: "age" }, { add: "add" }]
const result = Object.keys(Object.assign({}, ...data))
console.log(result)
The main reason for this is due to the fact that you are dealing with an array and Object.keys
expects an object to work.
answered Dec 7, 2018 at 3:24
First off that could be done much easier in a reduce
const test = [{hdr: "date"}, {hdr: "name"}, {hdr: "age"}, {hdr: "add"}];
const results = test.reduce((result, item) => [...result, { [item.hdr]: item.hdr }], []);
// This logs, ["0", "1", "2", "3"] because it is an array and the keys are integers.
console.log(Object.keys(results));
// If you want the object keys for each item in the array try mapping each item in the array to it's first key in the keys for that item
console.log(results.map(item => Object.keys(item)[0]));
answered Dec 7, 2018 at 1:54
1 Comment
Eem Jee
I can now understand better. But the situation is not like that. It's like this :
const results = [{date : "date"}, {name: "name"}, {age: "age"}, {add: "add"}]
. Thanks :)lang-js
Object.keys(this.hdr)
?.hdr
looks like a property of each object in thethis.test
array.