I have a very simple use case scenario:
I have 2 arrays:
var mainArray = [{"name": "Mike", "gender": "male"}, {"name": "Tom", "gender": "male", "email": "tom@yahoo.com"}, {"name": "John", "gender": "male", "phoneNumber": "123456"}];
var allKeysFormatted = ["name", "gender", "email", "phoneNumber"];
mainArray.forEach(function(arrObj){
allKeysFormatted.forEach(function(key){
arrObj[key] = arrObj[key] || null;
});
});
console.log(JSON.stringify(mainArray));
I want to have all the indexes in the mainArray
in the same order as allKeysFormatted
.If the key is not in the object, it will place there with null value.
But the problem I am facing is the position of keys are not maintaining its position, it gets changed. Like sometime I get email in the very first place of object.
Can someone help me with this?