Ilias Bennani
Ilias Bennani

Reputation: 247

Extract part of a Json object using Javascript

Let's say I have this object:

{
"cars":[
    {"modell":"Volvo", "color":"blue", "origin":"Sweden"}, 
    {"modell":"SAAB", "color":"black", "origin":"Sweden"},
    {"modell":"Fiat", "color":"brown", "origin":"Italy"},
    {"modell":"BMW", "color":"silver", "origin":"Germany"}, 
    {"modell":"BMW", "color":"black", "origin":"Germany"},
    {"modell":"Volvo", "color":"silver", "origin":"Sweden"}
    ]
}

First, I save the object to myCars.

1: I'd like to use javascript to extract the cars with the origin Sweden and then put those cars in a new object called mySwedishCars.

2: If that is more simple, I'd like to extract all non-swedish cars from the object myCars.

At the end, I would have to have an object that contains only Swedish cars.

Any suggestion would be welcome!

Upvotes: 0

Views: 4138

Answers (2)

Andy
Andy

Reputation: 63587

Use filter on the array of cars to return only the Swedish ones:

const myCars={cars:[{modell:"Volvo",color:"blue",origin:"Sweden"},{modell:"SAAB",color:"black",origin:"Sweden"},{modell:"Fiat",color:"brown",origin:"Italy"},{modell:"BMW",color:"silver",origin:"Germany"},{modell:"BMW",color:"black",origin:"Germany"},{modell:"Volvo",color:"silver",origin:"Sweden"}]};

function getSwedish(arr) {
  return arr.filter(el => {
    return el.origin === 'Sweden';
  });
}

console.log(getSwedish(myCars.cars));

BUT! Even better, you can generalise the function to return whatever nationality of car you like:

const myCars={cars:[{modell:"Volvo",color:"blue",origin:"Sweden"},{modell:"SAAB",color:"black",origin:"Sweden"},{modell:"Fiat",color:"brown",origin:"Italy"},{modell:"BMW",color:"silver",origin:"Germany"},{modell:"BMW",color:"black",origin:"Germany"},{modell:"Volvo",color:"silver",origin:"Sweden"}]};

function getCarsByCountry(arr, country) {
  return arr.filter(el => {
    return el.origin === country;
  });
}

console.log(getCarsByCountry(myCars.cars, 'Sweden'));
console.log(getCarsByCountry(myCars.cars, 'Germany'));

Upvotes: 2

PMerlet
PMerlet

Reputation: 2594

You can filter your array in javascript :

var swedishCars = myCars.cars.filter(function(c) {
    return (c.origin === "Sweden");
});

Upvotes: 1

Related Questions