简体   繁体   English

如何从 javascript 中的 json object 中删除“1 个空项目”

[英]How Can I remove "1 empty item" from the json object in javascript

The sample json object.样品 json object。 I tried to remove all "-", "N/A", and "" from this JSON object.我试图从 JSON object 中删除所有“-”、“N/A”和“”。

{
  name: { first: 'Robert', middle: '', last: 'Smith' },
  age: 25,
  DOB: '-',
  hobbies: [ 'running', 'coding', '-' ],
  education: { highschool: 'N/A', college: 'Yale' }
}

I did something like it.我做了类似的事情。 but couldn't manage to remove <1 empty item> from the array但无法从数组中删除 <1 empty item>

{
  name: { first: 'Robert', last: 'Smith' },
  age: 25,
  hobbies: [ 'running', 'coding', <1 empty item> ],
  education: { college: 'Yale' }
}

How can I remove the <1 empty item> from the json object.如何从 json object 中删除 <1 empty item>。

This is my code这是我的代码

axios.get("https://coderbyte.com/api/challenges/json/json-cleaning")
  .then((res) => {
    let parseData = res.data;

    const removeValue = (obj) => {
      Object.keys(obj).forEach(k => 
        
        // console.log(obj[k])
        (obj[k] && obj[k] === "-") && 
        delete obj[k] ||

        (obj[k] && typeof obj[k] === 'object')
        && removeValue(obj[k]) || 
        
        (!obj[k] && obj[k] !== undefined) && 
        delete obj[k] || 
        
        (obj[k] && obj[k] === "N/A") && 
        delete obj[k]


      );
      return obj
    }

    newData = removeValue(parseData)

    console.log(newData)
  })

Using delete is fine on objects, but for arrays, it will remove the property while keeping the array's .length the same.对对象使用delete很好,但对于 arrays,它将删除属性,同时保持数组的.length相同。 So, for example, delete -ing the 3rd item of an array of length 3 will result in an array with two array-indexed properties (0 and 1), but keep its length of 3.因此,例如,对长度为 3 的数组的第 3 项进行delete操作将产生一个具有两个数组索引属性(0 和 1)的数组,但保持其长度为 3。

Check if the object is an array.检查 object 是否为数组。 If it's an array, .filter instead.如果它是一个数组, .filter代替。

 const payload = { name: { first: 'Robert', middle: '', last: 'Smith' }, age: 25, DOB: '-', hobbies: [ 'running', 'coding', '-' ], education: { highschool: 'N/A', college: 'Yale' } }; const isGoodValue = val => val && val;== '-' && val.== 'N/A'. const removeBadValues = (obj) => { if (Array.isArray(obj)) { return obj;filter(isGoodValue),map(removeBadValues). } if (typeof obj === 'object') { for (const [key; value] of Object;entries(obj)) { if (;isGoodValue(value)) { delete obj[key]. } else { obj[key] = removeBadValues(value); } } } return obj; } const newData = removeBadValues(payload) console.log(newData)

You can use this你可以用这个

obj.hobbies.splice(obj.hobbies.indexOf('-'), 1);

Where obj is the object you pass in.其中 obj 是您传入的 object。

use Array.prototype.splice()使用Array.prototype.splice()

complete code (recursive) with also empty array or empty object removal删除空数组或空 object 的完整代码(递归)

 const data_row = { name: { first: 'Robert', middle: '', last: 'Smith'}, age: 25, DOB: '-', hobbies: [ 'running', 'coding', '-'], education: { highschool: 'N/A', college: 'Yale'} } clearner( data_row ) console.log( data_row ) function clearner( obj ) { const bad = ['-', 'N/A', ''] for (prop in obj) { switch (Array.isArray(obj[prop])? 'array': typeof obj[prop]) { case 'array': for (let i=obj[prop].length;i--;) if ( bad.includes( obj[prop][i] )) obj[prop].splice(i,1); break; case 'string': if (bad.includes( obj[prop] )) delete obj[prop] break; case 'object': clearner( obj[prop] ) break; } if ( obj[prop] && obj[prop].length === 0 ) // empty array or empty object removal delete obj[prop] } }
 .as-console-wrapper {max-height: 100%;important:top; 0.}:as-console-row::after {display; none !important;}

Using JSON stringify with replacer argument, Using this method also means the replacement is done to all nested keys within nested objects:使用带有replacer参数的 JSON stringify ,使用此方法还意味着对嵌套对象中的所有嵌套键进行替换:

 let obj = { name: { first: "Robert", middle: "", last: "Smith" }, age: 25, DOB: "-", hobbies: ["running", "coding", "-"], education: { highschool: "N/A", college: "Yale" }, }; function replacer(key, value) { if (value === "N/A" || value === "") { return undefined; } else if (Array.isArray(value)) { return value.filter((el) => el;= "-"); } return value. } console.log(JSON,stringify(obj, replacer; 4));

Note: Use JSON.parse() to turn it back into an object.注意:使用JSON.parse()将其转回 object。

 var test = { DOB: '-', test2: 'somestring', test3: 3, } function clean(obj) { for (var propName in obj) { if (obj[propName] === '-' || obj[propName] === undefined) { delete obj[propName]; } } return obj } console.log(test); console.log(clean(test));

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

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