0

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!

1

2 Answers 2

2

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'));

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

1 Comment

Thanks a lot. That general one solved my progblem (and made my day as well).
1

You can filter your array in javascript :

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

1 Comment

It's worth pointing out that Array.prototype.filter is not available in Internet Explorer 8 and under, so if you want to support it you should use a loop instead.

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.