It is necessary for each object in the array to check all the properties and return a new array of objects with primitive types. Those. from the array

[ { name: 'Ivan', definition: { head: true } }, { name: 'Fedor', definition: { head: false } } ] 

We get an array of objects that do not have properties of type object

  [ { name: 'Ivan'}, { name: 'Fedor'} ] 

How can such a parsing be organized?

  • Is a function a primitive type? - Grundy

3 answers 3

There are three tasks in the question:

  1. Check the value for primitiveness
  2. Create a new object based on the old, without some keys.
  3. Build a new array based on the old one.

To solve the first one, you need to decide what to consider as primitive types: if only strings and numbers are one condition, if in addition to them there is also null , undefined , function is another.

For example, take only strings and numbers, then the test can be made into such a function isPrimitive

 function isPrimitive(o){ return typeof o == 'string' || typeof o == 'number'; } 

To solve the second, you can use the reduce function: by applying it to an array of keys, you can collapse it into an object without unnecessary properties, for example, weaving:

 Object.keys(o).reduce((acc,key)=>{ if(isPrimitive(o[key])) acc[key] = o[key]; return acc; },{}); 

To solve the third one, use the map function.

Assembly may look like this:

 var array = [{ name: 'Ivan', definition: { head: true } }, { name: 'Fedor', definition: { head: false } }]; function isPrimitive(o) { return typeof o == 'string' || typeof o == 'number'; } var newArray = array.map(o => Object.keys(o).reduce((acc, key) => { if (isPrimitive(o[key])) acc[key] = o[key]; return acc; }, {})); console.log(newArray); 

    Or using ES6:

     let array = [{ name: 'Ivan', definition: { head: true } }, { name: 'Fedor', definition: { head: false } }]; let newArray = array.map(entry => { let newEntry = {}; Object.keys(entry).forEach(key => { let value = entry[key]; if (typeof(value) != 'object') { newEntry[key] = value; } }); return newEntry; }); console.log(newArray); 

    • "cycles, anyway" :) - Bookin
    • @Bookin, you're right :) Just for me personally, the entry in ES6 looks a bit more readable, even though it was not the subject of the question. - anatolii
    • for me, on the contrary, although I understand what is happening, but with all these arrows, the brain does not want to perceive the picture. Well, yes, yes, ES6 to the masses, so far where it is found in examples. - Bookin

    Cycles anyway:

     var test = [{ name: 'Ivan', definition: { head: true } }, { name: 'Fedor', definition: { head: false } }]; var newArray = []; for (var i in test) { var obj = {}; for (var j in test[i]) { if (typeof test[i][j] != 'object') { obj[j] = test[i][j]; } } newArray.push(obj); } console.log(newArray); 

    • it is better to make the first cycle usual for , or for..of , and not for..in - Grundy