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 }
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);
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>
@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]]);
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);
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.