[英]Filtering an array of objects by an object property within an object within the array
I'm in a nested hell of objects, here. 我在这里是一个嵌套的对象地狱。 I feel like there's an answer to this, I just can't quite figure out how to phrase what's happening. 我觉得这是有答案的,我只是想不出如何表达正在发生的事情。
So, I get this giant array of objects from a REST return (something like 450+ objects) that comes loaded like this: 因此,我从REST返回中获得了庞大的对象数组(类似于450多个对象),它是这样加载的:
results[0] = {
prop0: "String",
prop1: "String",
prop2: bool,
prop3: Object {
prop0: "String"
}
prop4: "String"
}
I'm doing this thing, first, where I'm creating an array of objects that contains just the unique strings out of that nested object's property, along with a count of the number of times that string appears within the data set. 我正在做这个事情,首先,我要创建一个对象数组,其中只包含该嵌套对象的属性之外的唯一字符串,以及该字符串在数据集中出现的次数。
I now need, for each unique string, to create an array of objects within the original dataset where results.prop3.prop0 matches the string in the collapsed array. 我现在需要为每个唯一字符串在原始数据集中创建一个对象数组,其中results.prop3.prop0与折叠数组中的字符串匹配。 Was that confusing enough? 这足够令人困惑吗?
From this: 由此:
Name: "Joe", 姓名:“乔”,
Place: state { 地点:州{
state: "New York", 州:“纽约”,
}, },
Alive: false 活着:假
} }
To this: 对此:
New York (120) 纽约(120)
Joe - Dead 乔-死了
I've gotten this far, using underscore.js: 到目前为止,我使用underscore.js:
for(index in collapsed){
var details = _.where(results,{state: {state: collapsed[index][0]}});
console.log(details);
}
But I'm clearly an idiot somewhere, because that's just returning an empty array for each thing in my collapsed array. 但是我显然在某个地方是个白痴,因为那只是为折叠数组中的每件事返回一个空数组。
Sample of collapsed 倒塌的样品
[{"New York",120},{"Georgia",79},{"Another Place",15}]. [{“ New York”,120},{“ Georgia”,79},{“ Another Place”,15}]。
I basically want to build a table of data where, underneath each place, I load in the objects where Place matches the state string all the way at the bottom of the nested object. 我基本上想建立一个数据表,在每个地方的下面,我将要装载的对象放置在嵌套对象底部一直与状态字符串匹配的对象上。
To jm_____'s point, I'm going to try that. 就jm_____而言,我将尝试一下。
Here are examples of data manipulation with underscore based on _.reduce()
and _.filter()
这是基于_.reduce()
和_.filter()
带下划线的数据处理示例
Getting collapsed array with number of items grouped by states 获取折叠的数组,其中包含按状态分组的项目数
var collapsed = _.reduce(response, function(memo, item) {
if ( ! memo[item.Place.state]) {
memo[item.Place.state] = 0;
}
memo[item.Place.state]++;
return memo;
}, {});
Result: grouped object with states as keys and count as values. 结果:将状态作为键的对象分组,并将其计数为值。
{
London: 2,
New York: 4
}
Getting filtered data by state 按状态获取过滤数据
var filtered = _.filter(response, function(item) {
return item.Place.state === "New York";
});
Result: array of objects with only state New York 结果:仅具有纽约州的对象数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.