简体   繁体   English

从JavaScript对象递归添加和删除值

[英]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. 因此,我正在使用来自API的数据在React中构建基本的方面搜索,但是我正努力从发送回服务器的有效负载中添加和删除值。 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... 使用deepmerge,我可以将多个值传递回API,而API可以正常工作,因此示例有效负载将是...

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" 清除搜索,要删除的值=“ Luther”
Toggle of topic, value to remove = "9832748273" 切换主题,要删除的值=“ 9832748273”
Toggle of genre, value to remove = "3827487483" 类型的切换,要删除的值=“ 3827487483”
Toggle of rating, value to remove = "18" 切换等级,要删除的值=“ 18”
Toggle of type, value to remove = { args: { when: "today", min: 15}, name: "spot"} 类型的切换,要删除的值= { 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 我只是使用delete关键字删除对象属性,像这样

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 代码示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM