1

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
  • How are you calling Object.keys(this.hdr)? .hdr looks like a property of each object in the this.test array. Commented Dec 7, 2018 at 1:47
  • @achacttn Opppss updated. Variable name typo :) Commented Dec 7, 2018 at 1:54

2 Answers 2

5

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

2 Comments

Just a question, what does ... mean? Thanks.
It is ES6 spread operator, which basically gets all the objects and lists them as parameters to the Object.assign function
0

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

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 :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.