1

I have an array of JSON objects

array = [{name: "will", age: "18"}
         {name: "Elliott", age: "21"}
        ] 

Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?

2 Answers 2

3

Yes.

let array = [
  { name: "will", age: "18"}, 
  { name: "john", age: "18"}, 
  { name: "elliott", age: "21"}
]

array.filter((e) => { return e.name === 'john' })

Result

[ { name: 'john', age: '18' } ]
Sign up to request clarification or add additional context in comments.

2 Comments

To extend this, is there a way of editing the "name" and "age" of those indexes in the array without removing the entire object and adding a new one?
As far as I know you can't in Typescript easily. You must use map to extending your object type
0
let queryName = 'will';
array.forEach((obj) => {
    if (obj.name === queryName) {
        console.log(obj.name, obj.age); // will 18
    }
});

Comments

Your Answer

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.