简体   繁体   中英

Filter JavaScript Array of Objects based on Objects Key

I have an array of objects I generated from a JSON response.

The content of said array is structured like this:

const array = [
{title: "user generated title", message: "random user generated text", status: "Active/Inactive"},
 {200 + more objects with the exact same key/values as the first},
...,
...
]

I want to make a new array with the exact same objects minus specific key/value pairs.

Ie, to make the exact same array with out say all message: "user message" key/value pairs. (There are multiple key/value pairs I want to remove from the objects in the array though.)

so it would be like

const array = [
{title: "user generated title", status: "Active/Inactive"},
{200 + objects just like the first without the message: "message text"},
...,
...
]

You could go over them and delete those keys:

array.forEach(o => delete o.message); 
var newArray = [];
for (var i = 0; i < array.length; i++) {
    var obj = array[i];
    
    if (!("message" in obj)) { //put the conditions to keep the object here
        newArray.push(obj); //copy reference to new array
    }
}

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