1

In typescript, I have an array of objects. I want to create a new array with the headers of the objects from the first array.

    let scores = [{name: "A", skills: 50, result: 80},
                  {name: "B", skills: 40, result: 90},
                  {name: "C", skills: 60, result: 60}];

    let parameters = Array.from(this.scores.keys());
    this.console(parameters);

    // parameters = [0, 1, 2]

    // expecting; parameters = ["name", "skills", "result"]
0

2 Answers 2

6

You could get the keys from the first object of the array.

let scores = [{ name: "A", skills: 50, result: 80 }, { name: "B", skills: 40, result: 90 }, { name: "C", skills: 60, result: 60 }],
    parameters = Object.keys(scores[0]);
   
console.log(parameters);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answering my query. Need one more suggestion. What to do if I wanted parameters = ["skills", "result"]. Don't want the "name" object to be included in the parameters.
you could filter the array with keysWithoutName = keys.filter(k => k !== 'Name');
1

If you can have different objects with different keys you can use .reduce() and then get the Object.values() of your accumulated object:

const scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {x: "C", y: 60, z: 60}];

const res = Object.values(scores.reduce((acc, obj) => {
  const key = Object.keys(obj);
  acc[key] = acc[key] || key;
  return acc;
}, {}));

console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.