简体   繁体   中英

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!

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

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

var mySwedishCars = getSwedish(myCars.cars);

DEMO

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

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

var mySwedishCars = getCarsByCountry(myCars.cars, 'Sweden');
var myGermanCars = getCarsByCountry(myCars.cars, 'Germany');

DEMO

You can filter your array in javascript :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM