skip to Main Content

I have a requirement where I want to add null values for properties which are non existent in the array of objects. I don’t want to loop over

var data=[
    {
        "id": 1,
        "name": "John"
    },
    {
        "id": 2
    },
    {
        "id": 3
    }
]

Expected result is as follows

[
    {
        "id": 1,
        "name": "John"
    },
    {
        "id": 2,
        "name": null
    },
    {
        "id": 3,
        "name": null
    }
]

3

Answers


  1. Map array so if name is undefined set it to null, otherwise leave the same value:

    const result = data.map(item => ({...item, name: item.name ?? null}))
    
    Login or Signup to reply.
  2. Little for each loop will do that. Also I think || would be better than ??, here is why:
    When should I use ?? (nullish coalescing) vs || (logical OR)?

    const data =[
        {
            "id": 1,
            "name": "John"
        },
        {
            "id": 2
        },
        {
            "id": 3
        }
    ]
    
    data.forEach(set => { set.name = set.name || null })
    console.log(data)

    Ah sorry, didn’t notice the part with the loop in the question. I still let this answer be here.

    Login or Signup to reply.
  3. One further option is the following, with explanatory comments in the code; this answer assumes that the keys may have to be found prior to adding them to the Object:

    // the initial Array of Objects:
    const data = [{
        id: 1,
        name: "John",
      },
      {
        id: 2,
      },
      {
        id: 3,
      }
    ],
    
    // a simple function, declared using Arrow function syntax,
    // which takes one argument, an Array of Objects:
    getAllKeys = (objectArray) => {
    
      // we return an Array formed from a Set, by use of the
      // spread syntax and an Array literal:
        return [...new Set(
            // we form the Set from the reduced Array of Objects,
            // created using Array.prototype.reduce():
            objectArray.reduce(
              // the Array.prototype.reduce() method has the
              // arguments of 'acc' (the accumulator formed
              // by the method), and the 'curr' Object (the
              // current Object of the Array of Objects):
              (acc,curr) => {
                // within the Arrow function, we simply
                // push the keys of the current Object -
                // retrieved with Object.keys - to the
                // accumulator Array, which we then flatten
                // using Array.prototype.flat():
                acc.push(Object.keys(curr));
              return acc.flat();
            // the empty Array-literal here is the accumulator
            // used within the method:
            },[]
          )
        )];
      },
    // here we use the function to retrieve an Array of the
    // keys from Objects in the data Array:
    keys = getAllKeys(data),
    
    // we then use Array.prototype.map() to iterate over the
    // data Array and create a new Array from that Array:
    newData = data.map((obj) =>{
      // we return a new Object, created using Object.fromEntries():
        return Object.fromEntries(
        // we use Array.prototype.map() to iterate over the
        // Array of Object properties:
        keys.map(
          // 'k' is the value of the current Object property
          // ('k' standing for 'key' in this case);
          // we return a new two-part Array formed from the
          // current Object property-name, and the existing
          // property-value of the current Object's property
          // of that name, or null (if no property-value
          // exists):
          (k)=> [k, obj[k] || null]
        )
      );
    });
    
    console.log(newData);
    /*
      [
        {
          id: 1,
          name: "John"
        },
        {
          id: 2,
          name: null
        },
        {
          id: 3,
          name: null
        }
      ]
    
    */

    JS Fiddle demo.

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search