简体   繁体   中英

Recursively adding and removing values from javascript object

So I'm building a basic facet search in React using data from an API, but I'm struggling with the adding & removing of values from the payload sent back to the server. The payload object can contain Arrays, Objects & Strings. So say I have a payload structure like the following:

payload = {
   search_query: ""
   topic: [],
   genre: [],
   rating: "",
   type: {}
}

Using deepmerge I'm able to pass multiple values back to the API which is working fine, so an example payload would be...

payload = {
   search_query: "Luther"
   topic: ["9832748273", "4823794872394"],
   genre: ["3827487483", "3287483274873"],
   rating: "18",
   type: {
     args: {
       when: "today",
       min: 15
     },
     name: "spot"
   }
}

So far so good, I get the expected results back. Now I have a toggle on the facet to remove it from the payload, which sends back the value to a function to remove from the payload. For example:

Clear Search, value to remove = "Luther"
Toggle of topic, value to remove = "9832748273"
Toggle of genre, value to remove = "3827487483"
Toggle of rating, value to remove = "18"
Toggle of type, value to remove = { args: { when: "today", min: 15}, name: "spot"}

Search & Rating would return empty strings, topic & genre would remove items from the arrays and type would return an empty object.

This works for removing the array values but feels dirty and I want a clean way to handle all types!

const removeObjValue = (obj, filterValue) => {
  Object.entries(obj).forEach(([key, value]) => {
    Object.entries(value).forEach(([subKey, subValue]) => {
      if(subvalue === filterValue) {
        if(Array.isArray(value)) {
          const index = value.indexOf(subvalue);
          if (index > -1) {
            value.splice(index, 1);
          }
        }
      }
    });
  });
  return obj;
}

I just use delete keyword to remove object attributes, like this

if (payload[key]) {
 if (payload[key] instanceof Array) {
    var idx = payload[key].indexOf(value);
  if (idx > -1) payload[key].splice(idx, 1);
 } else {
    delete payload[key];
 }
}

code example

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