Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
how to set object keys to common denominators?

I have an array of objects and want every object in the array to have the same keys.

var obj1 = {"type": "test", "info": "a lot", "value": 7};
var obj2 = {"value": 5};
var obj3 = {"context": "demo", "info": "very long", "value": 3};
var obj4 = {"info": "no way"};

var dataSet = [obj1,obj2,obj3,obj4];

My attempt is to create an array with all possible keys in the first step. Then loop through that keys array and update the objects if the key was not found.

keys.forEach(function(a,b){
  dataSet.forEach(function(c,d){    
    //key not found
    if(a in c === false)
    {
      //add key to object 
      dataSet[b][a] = false;
    }
  });
});

Howewer, it does not seem to work correctly. This is my output:

after logic:  [
  {
    "type": false,
    "info": "a lot",
    "value": 7
  },
  {
    "value": 5,
    "info": false
  },
  {
    "context": "demo",
    "info": "very long",
    "value": false
  },
  {
    "info": "no way",
    "context": false
  }
]

What am I missing there?

var obj1 = {"type": "test", "info": "a lot", "value": 7};
var obj2 = {"value": 5};
var obj3 = {"context": "demo", "info": "very long", "value": 3};
var obj4 = {"info": "no way"};

var dataSet = [obj1,obj2,obj3,obj4];
var keys    = [];

console.log("before logic: ", dataSet);

//Step 1: Fill keys array
dataSet.forEach(function(a,b){  
  Object.keys(a).forEach(function(c,d)
  {
    //add keys to array if not already exists
    if(!keys.includes(c))
    {
      keys.push(c);
    }
  });
});

//Step2: loop through keys array and add key to object if not existing
keys.forEach(function(a,b){
  dataSet.forEach(function(c,d){    
    //key not found
    if(a in c === false)
    {
      //add key to object 
      dataSet[b][a] = false;
    }
  });
});

console.log("after logic: ", dataSet);

EDIT:

It would be perfect if the keys are always sorted in the same order too.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can just collect the keys in a Set using flatMap(), and then assign the missing ones using forEach():

const dataSet = [
  {"type": "test", "info": "a lot", "value": 7},
  {"value": 5},
  {"context": "demo", "info": "very long", "value": 3},
  {"info": "no way"}
];

const keys = new Set(dataSet.flatMap(Object.keys));

dataSet.forEach((v) => keys.forEach((k) => v[k] = k in v ? v[k] : false));

console.log(dataSet);


To address the additional request of having the keys in the same order, note that historically, JavaScript object properties were unordered, so relying on the order of object properties in JavaScript is almost never a good idea.

That being said, it's hard to get a fixed order when modifying the existing objects, but doable if you create new objects:

const dataSet = [
  {"type": "test", "info": "a lot", "value": 7},
  {"value": 5},
  {"context": "demo", "info": "very long", "value": 3},
  {"info": "no way"}
];

const keys = [...new Set(dataSet.flatMap(Object.keys))];

const result = dataSet.map((v) => keys.reduce((a, k) => ({
  ...a,
  [k]: k in v ? v[k] : false
}), {}));

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

The problem with your code is basically a typo: You're using the wrong index when you set the key:

dataSet[b][a] = false;

b is the index of the key in keys, not the index of the object in dataSet. You don't need to do that indexing at all, just do:

c[a] = false;

It's much easier to follow what you're doing and such when you use meaningful names for variables rather than a, b, c, and d. Here's your code with some reasonable renaming and with the change described above:

var obj1 = { type: "test", info: "a lot", value: 7 };
var obj2 = { value: 5 };
var obj3 = { context: "demo", info: "very long", value: 3 };
var obj4 = { info: "no way" };

var dataSet = [obj1, obj2, obj3, obj4];
var keys = [];

console.log("before logic: ", JSON.stringify(dataSet, null, 4));

//Step 1: Fill keys array
dataSet.forEach(function (obj) {
  Object.keys(obj).forEach(function (key) {
    //add keys to array if not already exists
    if (!keys.includes(key)) {
      keys.push(key);
    }
  });
});

//Step2: loop through keys array and add key to object if not existing
keys.forEach(function (key) {
  dataSet.forEach(function (obj) {
    //key not found
    if (key in obj === false) {
      //add key to object
      obj[key] = false;
    }
  });
});

console.log("after logic: ", JSON.stringify(dataSet, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

But that code can be much simpler using a Set and modern language features:

const obj1 = { type: "test", info: "a lot", value: 7 };
const obj2 = { value: 5 };
const obj3 = { context: "demo", info: "very long", value: 3 };
const obj4 = { info: "no way" };

const dataSet = [obj1, obj2, obj3, obj4];
const keys = new Set(); // *** Use a set

console.log("before logic: ", dataSet);

// Step 1: Fill keys array
for (const obj of dataSet) {
    for (const key of Object.keys(obj)) {
        keys.add(key);
    }
}

// Step2: loop through keys array and add key to object if not existing
for (const key of keys) {
    for (const obj of dataSet) {
        if (!(key in obj)) {
            obj[key] = false;
        }
    }
}

console.log("after logic: ", JSON.stringify(dataSet, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

Robby Cornelissen takes it much further, but I wanted to show using simple loops.

about 4 years ago · Juan Pablo Isaza Report

0

You can create a 'template' object from the Set of combined keys and then simply Object.assign to this template from each object. This will give you all the properties in a consistent order.

const dataSet = [
  { "type": "test", "info": "a lot", "value": 7 },
  { "value": 5 },
  { "context": "demo", "info": "very long", "value": 3 },
  { "info": "no way" }
];

const template = Object.fromEntries([...new Set(dataSet.flatMap(o => Object.keys(o)))].map(k => [k, false]));

const result = dataSet.map(o => Object.assign({ ...template }, o));

console.log(result)

Alternatively you can create the template by simply merging all the objects in the data set and overwriting a default value.

const dataSet = [
  { "type": "test", "info": "a lot", "value": 7 },
  { "value": 5 },
  { "context": "demo", "info": "very long", "value": 3 },
  { "info": "no way" }
];

const template = Object.assign({}, ...dataSet);

for (const k of Object.keys(template)) {
  template[k] = false;
}

const result = dataSet.map(o => Object.assign({ ...template }, o));

console.log(result)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!