Home > Back-end >  How to extract a specific item from a array of Typescript objects?
How to extract a specific item from a array of Typescript objects?

Time:05-17

I am new to Typescript, can you help me with this-

I have an array of objects, -

[{Name: a,
  Age: 1
 },
 {Name: b,
  Age: 2
 }
]

I want an array which should be - [a, b]

I tried with the following but I am not getting the expected result-

for (int i=0; i< treeData.length; i  ) {
    finalArray.push(treeData[i][0]);
}
console.log(finalArray);

Can anyone please help me out. Thanks in advance..

CodePudding user response:

First of all, this is invalid syntax:

for (int i=0; i< treeData.length; i  ) {

int is not a valid typescript type, and if it was, that is not the right syntax to use it. You need to create a variable there, which will be implicitly typed from its initial value.

for (let i=0; i< treeData.length; i  ) {

Secondly, here:

finalArray.push(treeData[i][0]);

You have an array of objects. You are trying to index the array with an integer i, which is fine. But then you are trying to index the objects in that array with another integer 0, which is not valid. Objects are indexed by the name of their keys, not the index of their keys.

That means you need to ask each object for the Name property.

finalArray.push(treeData[i].Name);

Putting that all together looks like this:

const treeData = [
    { Name: "a", Age: 1 },
    { Name: "b", Age: 2 },
]

const finalArray: string[] = []

for (let i=0; i< treeData.length; i  ) {
    finalArray.push(treeData[i].Name);
}
console.log(finalArray); // ['a', 'b']

See playground


Although, this is a lot more code than you need. It's best to avoid indexed loops in favor of iterating over the array elements.

In this case if you want to derive a value from each element of an array. That's called a map operation:

const treeData = [
    { Name: "a", Age: 1 },
    { Name: "b", Age: 2 },
]

const finalArray = treeData.map(obj => obj.Name)

console.log(finalArray); // ['a', 'b']

See playground

CodePudding user response:

you can use map here:

documentation to map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

let treeData = [
    { Name: "a", Age: 1 },
    { Name: "b", Age: 2 },
]

var finalArray = treeData.map(item => item.Name)
console.log(finalArray) // ['a', 'b']
  • Related