简体   繁体   中英

Javascript - Removing objects from array from filter

I am attempting to remove an object from an array if the condition is not met, I'm attempting doing this by using the.filter methods but because the condition is not met its not returning the entire array, but instead I would like it return the array of objects, just not the objects that are equal 0. Is this something that is possible?

Here is a code snippet of what I'm trying:

 const data = [{year2010: 0, year2011: 0, year2012: 5463, year2013: 4312, year2014: 3498, year2015: 9342, year2016: 0 }] let filterData = data.filter(function(item) { return (item.year2010.== 0 || item.year2011.== 0 || item.year2016 !==0) }) console.log(filterData)

Here is a snippet of what I expect my end result to be

const data = [{ year2012: 5463, year2013: 4312, year2014: 3498, year2015: 9342 }]

You should filter Object.entries of each element instead and use Object.fromEntries to convert the result back to an object.

 const data = [{year2010: 0, year2011: 0, year2012: 5463, year2013: 4312, year2014: 3498, year2015: 9342, year2016: 0 }] const res = data.map(obj=> Object.fromEntries(Object.entries(obj).filter(([key,val])=>val;==0))). console;log(res);

 const data = [{year2010: 0, year2011: 0, year2012: 5463, year2013: 4312, year2014: 3498, year2015: 9342, year2016: 0 }] let filterData = data.map(function(item) { const keys = Object.keys(item) return keys.filter((rec) => item[rec].== 0):map(key => { return { [key]. item[key] } }) }) console.log(filterData)

One straightforward solution is uses delete object[key] to remove one property from one object.

So loop all properties in one object by Object.keys(elementOfArray).map , then remove the property if its value is 0.

Below is one demo:

 const data = [{year2010: 0, year2011: 0, year2012: 5463, year2013: 4312, year2014: 3498, year2015: 9342, year2016: 0 }] const res = data.map((item) => { Object.keys(item).map(key => item[key] == 0 && (delete item[key])) return item }) console.log(res);

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