简体   繁体   English

使用Underscore.js过滤和合并json

[英]Using Underscore.js to filter and merge json

I have a use case where I need to use underscore.js to filter a JSON. 我有一个用例,其中需要使用underscore.js来过滤JSON。 For example 例如

{"test":{
{ key: 1,country:USA,product:A,price:200}
{key: 1,country:USA,product:B,price:200}
{key: 1,country:UK,product:B,price:300}
}
}

I have multiple dimensions for same key. 我为同一个键有多个尺寸。 I need to get the output as follows when i filter USA 我过滤美国时需要获得如下输出

{"test":{
{ key: 1,country:USA,price:400}
}
}

and when I filter for product B 当我过滤产品B时

{"test":{
{ key: 1,product:B,price:500}
}
}

I'd like to implement this using underscore.js as I believe it is fast compared to pure JS options. 我想使用underscore.js来实现这一点,因为我认为与纯JS选项相比,它的速度很快。

Firstly, try to use underscore _.filter to apply searching with your criteria like product or country. 首先,尝试使用下划线_.filter来根据您的条件(例如产品或国家/地区)应用搜索。

Then do an aggregation based on result from filter by simply use _.each function. 然后,只需使用_.each函数,即可根据过滤器的结果进行汇总。

Finally, you can manipulate your result in _.map function. 最后,您可以在_.map函数中处理结果。

I posted jsfiddle link here, it might help you 我在这里发布了jsfiddle链接,它可能对您有帮助

jsfiddle.net/zusquang/39os1854/

I'm doing hope this help. 我在希望得到帮助。

I'm assuming you have a typo and test contains an array of objects: 我假设您有一个错字,并且测试包含一个对象数组:

var filtered = JSON.parse(jsonString).test.filter(function(item) { return item.country == 'USA' });
var total = 0;

filtered.forEach(function(item) {
    total += item.price
});

Don't worry about speed, this would be a micro-optimization, which is not recommended. 不必担心速度,这是微优化,不建议这样做。

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

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