-1

I have following JSON structure

myObj = {
  name: "John",
  age: 30,
  cars: [{ type: "car", year: "1998" }, { type: "van", year: "1995" }]
};

I need to get the year of the car where thepseudois = car

In pesudo code

myObj.cars.getElement(type=car).year

which should give me 1998 as the output.

Can I do this in Javascript without loops

I need to get the year of the car where the type is = car

In pesudo code

myObj.cars.getElement(type=car).year

which should give me 1998 as the output.

Can I do this in Javascript without loops

Vaibhav Bhavsar
  • 432
  • 4
  • 12
Malintha
  • 4,512
  • 9
  • 48
  • 82
  • 1
    Just fetch the entire array like `myObj.cars` and then use `.filter` to fetch the relevant nested objects inside the array – Mr. Alien Jul 17 '18 at 09:28
  • 3
    "I have following JSON structure" — That is JavaScript, not JSON. – Quentin Jul 17 '18 at 09:28
  • myObj.cars.find(o => o.type === "car").year , for your question this will work. Since find returns the first object that satisfies the condition – Learner Jul 17 '18 at 09:34

1 Answers1

0

You can use filter() and map():

let myObj ={
  "name":"John",
  "age":30,
  "cars":[ {"type":"car", "year":"1998"}, 
           {"type":"van", "year":"1995"}]
};

var carYear = myObj.cars.filter(c => c.type=='car').map(y=>y.year);
console.log(carYear);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • myObj.cars.find(o => o.type === "car").year , for the above question this will work. Since find returns the first object that satisfies the condition. Its a suggestion. – Learner Jul 17 '18 at 09:36