简体   繁体   English

使用Java脚本提取Json对象的一部分

[英]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 . 首先,我将对象保存到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 . 1:我想使用JavaScript提取起源于瑞典的汽车,然后将这些汽车放到名为mySwedishCars的新对象中。

2: If that is more simple, I'd like to extract all non-swedish cars from the object myCars . 2:如果更简单,我想从对象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: 在汽车阵列上使用filter仅返回瑞典的汽车:

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 : 您可以使用javascript过滤数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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