Search code examples
arraysnode.jsjsonjavascript-objects

NODEJS : Want To Create an Array of objects, with only one key's value set to empty in each Object


I have

obj1 = {
    "place": "{{base_gplaceId}}",
    "subPlace": "{{base_gsubPlaceId}}",
    "user": "{{base_userId}}",
};

I want

var newArr = [{
    "place": "",
    "subPlace": "{{base_gsubPlaceId}}",
    "user": "{{base_userId}}",
}, {
    "place": "{{base_gplaceId}}",
    "subPlace": "",
    "user": "{{base_userId}}"
}, {
    "place": "{{base_gplaceId}}",
    "subPlace": "{{base_gsubPlaceId}}",
    "user": ""
}];

Following is my Code

var newArr = [];
const obj1 = {
    "place": "{{base_gplaceId}}",
    "subPlace": "{{base_gsubPlaceId}}",
    "user": "{{base_userId}}",
};

KEYS = Object.keys(obj1);

KEYS.forEach(function (element) {
    var object2 = null;

    console.log("init:", object2);

    object2 = obj1;

    console.log("object2:", object2);

    console.log("element:", element);

    console.log("object2 element VAL:", object2[element]);

    object2[element] = "";

    console.log("OBJ VAL:", object2, "\n---------------");

    newArr.push(object2);
});

console.log(newArr);

Some how mid way obj1 is being set to empty values, and hence object2 is being set with empty values not getting Expected Values.


Solution

  • Objects are assigned by reference. When you set object2 = obj1; and then change object2, obj1 will change as well. Doing that in a loop causes the side effects you're seeing.

    Copy the object using object2 = Object.assign({}, obj1); instead.