Matt
Matt

Reputation: 1

How do I remove an array from an object?

I am attempting to write a function that iterates over a given object(obj). Each time it comes across an array within the object, it removes the array. The code seems appropriate, but please tell me what I'm missing:

function removeArrayValues(obj) {

  for (isKeyAnArray in obj) {
     if (typeof obj[isKeyAnArray] === 'array') {
       delete obj[isKeyAnArray];
    }
  }
}

var obj = {
  a: [1, 3, 4],
  b: 2,
  c: ['hi', 'there']
}

removeArrayValues(obj);
console.log(obj); // --> { b: 2 }

Upvotes: 0

Views: 78

Answers (4)

ZER0
ZER0

Reputation: 25322

Notice that this would not mutate the original object (just add as alternative answer in case it could help):

const newObj = Object.fromEntries(
  Object.entries(obj).filter(([, value]) => !Array.isArray(value))
)

console.log(newObj);

Upvotes: 0

Michael Cacciano
Michael Cacciano

Reputation: 389

@Gokhan Sari 's way of doing is exactly accurate. This is more of an add-on if you wanted to go the es6 or just hipster route :D

const removeArrayValues = obj => Object.entries(obj).forEach(val => Array.isArray(val[1]) && delete obj[val[0]]);

Upvotes: 0

CrandellWS
CrandellWS

Reputation: 2804

check if it is an array is another way. In the included code sample 2 variations are shown.

function removeArrayValues(obj) {

  for (isKeyAnArray in obj) {
     if (obj[isKeyAnArray] instanceof Array){
       console.log("instanceof array true");
       delete obj[isKeyAnArray];
     }
     if (Array.isArray(obj[isKeyAnArray])){
       console.log("isArray true");
       delete obj[isKeyAnArray];
     }
     console.log(typeof obj[isKeyAnArray]);
     if (typeof obj[isKeyAnArray] === 'array') {
       delete obj[isKeyAnArray];
    }
  }
}

var obj = {
  a: [1, 3, 4],
  b: 2,
  c: ['hi', 'there']
}

removeArrayValues(obj);
console.log(obj); // --> { b: 2 }
document.getElementById("exampleText").innerHTML = JSON.stringify(obj);
<p id="exampleText"></p>

Upvotes: 0

Gokhan Sari
Gokhan Sari

Reputation: 7924

typeof returns "object" for an array. You can use Array.isArray() to check if the property is an array.

Here is the modified version of your code:

function removeArrayValues(obj) {

  for (isKeyAnArray in obj) {
     if (Array.isArray(obj[isKeyAnArray])) {
       delete obj[isKeyAnArray];
    }
  }
}

var obj = {
  a: [1, 3, 4],
  b: 2,
  c: ['hi', 'there']
}

removeArrayValues(obj);
console.log(obj);

Upvotes: 2

Related Questions