-2

could you help me with code which delete all objects in array?

in my example i have array which contains Objects.

Every object contains keys and i want to look at every key and check if it is Object.

If it is Object i want to delete that key( In my example i just rewrite its value to empty string)

   if(typeof result2.length == 'number'){
    for(var u in result2){
    Object.keys(result2[u])
.filter(k => typeof result2[u][k] === 'object')
.map(k => delete result2[u][k])
}
}else{
    Object.keys(result2)
.filter(k => typeof result2[k] === 'object')
.map(k => delete result2[k])
}

My code which works if result2 containts more Objects.

If it contain only 1 object it does not work.

If input contain only 1 object its change from array to object.

Bobek
  • 757
  • 3
  • 7
  • 15

1 Answers1

0

Replace result2[u][p] = ""; on delete result2[u][p]

You can alse make it:

const object1 = {
  a: 'somestring',
  b: 42,
  c: {s: "dsdfsdf"}
};

Object.keys(object1)
.filter(k => typeof object1[k] === 'object')
.every(k => delete object1[k])

console.log(object1);
  • if i i edit your example it works, until my array contain only 1 object. if my array contains only 1 object it crash as my code. for(var u in result2){ Object.keys(result2[u]) .filter(k => typeof result2[u][k] === 'object') .map(k => delete result2[u][k]) console.log(result2); } – Bobek Aug 01 '18 at 08:12
  • Could you paste example of your object result2, that should not working for you? – Adrian Pażucha Aug 01 '18 at 09:13
  • It is on 2.input (bad scenario) Array contain only 1 Object(no Index). There is maybe problem that if array contains only 1 object its automatically change to Object – Bobek Aug 01 '18 at 09:15
  • It sounds like "above" logic generate incorrect data. – Adrian Pażucha Aug 01 '18 at 10:43