[英]manipulate array of hashes using javascript
Can you please show me the best way to process/ manipulate this array of hashes using javascript function chaining. 能否请您告诉我使用javascript函数链处理/操作此哈希数组的最佳方法。 I want to filter the data and return ONLY an array of hashes that contains data that in NOT all 0's. 我想过滤数据并仅返回包含不是全部为0的数据的哈希数组。
data = [
{name: "apple", data: [0, 0, 0]},
{name: "banana", data: [1, 0, 2]},
{name: "carrot", data: [0, 0, 0]},
{name: "pineapple", data: [0, 0, 3]},
]
//result after filtering
data = [
{name: "banana", data: [1, 0, 2]},
{name: "pineapple", data: [0, 0, 3]},
]
I was thinking something along the lines of 我在想一些类似的事情
data.filter((hash,i) => {hash.data.every((elem,i)=> elem == 0);
This should do it 这应该做
const data = [{name:”apple”,data:[0,0,0]}, {name:”banana”,data:[1,0,2]}, {name:””,carrot:[0,0,0]}, {name:”pineapple”,data:[0,0,3]}, ]
const nonzero = data.filter(({data}) => data.some(Boolean));
You were almost right. 你说的没错。 You need to invert the result of the every
test, since you want the elements that aren't all zero; 您需要反转的结果every
测试,因为你想要的元素并不都是零; you could also use some
and test for non-zero. 您还可以使用some
并测试非零值。 Also, don't put curly braces around the body of the function if you just want to return the result of the expression. 另外,如果只想返回表达式的结果,请不要在函数的主体周围使用花括号。
data = [{ name: "apple", data: [0, 0, 0] }, { name: "banana", data: [1, 0, 2] }, { name: "carrot", data: [0, 0, 0] }, { name: "pineapple", data: [0, 0, 3] }, ]; console.log(data.filter(hash => !hash.data.every(elem => elem == 0)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.