简体   繁体   English

如何从对象中删除数组值

[英]How to remove array values from an object

var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
   }
   removeArrayValues(obj);
   console.log(obj); // --> { b: 2 }

Here is my code: 这是我的代码:

function removeArrayValues(obj) {
 for (var key in obj){
 if (Array.isArray(obj[key])) delete obj[key]
 //return obj[key] -> {b: 2, c: ["hi", "there"]}
 }
 return obj[key]
}

Why does it return only obj["a"] and obj["c"] when I return it inside the for/in loop and not obj["k"] . 当我在for/in loop而不返回obj["k"]时,为什么只返回obj["a"]obj["c"] obj["k"] I figured the problem out right before I was about to post this but I run into this issue a lot with both arrays and objects and could use an explanation of what is going on here. 我在即将发布此问题之前就已经解决了这个问题,但是我在数组和对象上都遇到了很多问题,可以对这里发生的事情进行解释。

First, let's see your object. 首先,让我们看看您的对象。 It has 3 key/value pairs: 它具有3个键/值对:

var obj = {
    a: [1, 3, 4],//the value here is an array
    b: 2,//the value here is not an array
    c: ['hi', 'there']//the value here is an array
};

For each key in that object, your removeArrayValues function will delete any of them which has an array as value: 对于该对象中的每个键,您的removeArrayValues函数将删除其中任何一个具有数组作为值的键:

if (Array.isArray(obj[key]))

That condition will return "true" if the value is an array. 如果值是一个数组,则该条件将返回“ true”。 You can check this in this demo: the console.log inside the for loop will log "true", "false" and "true": 您可以在此演示中进行检查: for循环内的console.log将记录“ true”,“ false”和“ true”:

 var obj = { a: [1, 3, 4], b: 2, c: ['hi', 'there'] } removeArrayValues(obj); function removeArrayValues(obj) { for (var key in obj){ console.log(Array.isArray(obj[key])) if (Array.isArray(obj[key])) delete obj[key] //return obj[key] -> {b: 2, c: ["hi", "there"]} } return obj[key] } 

So, the first key will be removed ("true"), the second one will not ("false"), and the third one will be removed ("true"). 因此,第一个键将被删除(“ true”),第二个键将不会(“ false”),第三个键将被删除(“ true”)。

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

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