Group and extract properties in a javascript object by name

Viewed 50
obj = {
  data_a: 'a',
  data_b: 'b',
  user_a: 'a',
  user_b: 'b'
  // and many more
};

From the above object how can I group and extract properties based on their name? I'm trying to get all names beginning with data_ and then load them into a new object then do the same for the ones beginning with user_

What is a good way to do this?

4 Answers

You can do that in following steps:

  • Get all the entries of the object using Object.entries()
  • Use filter() on it and get all those entries in which key starts with required substring.
  • Use Object.fromEntries() to convert the entries back to object.

Here is the code

const obj = {
  data_a: 'a',
  data_b: 'b',
  user_a: 'a',
  user_b: 'b'
};

const filterByKey = (obj, string) => Object.fromEntries(Object.entries(obj).filter(([k, v]) => k.startsWith(string)))
console.log(filterByKey(obj, "data"));
console.log(filterByKey(obj, "user"))

You can iterate over the object, get the keys, and use indexOf function to classify them as follows:

obj = {
  data_a: 'a',
  data_b: 'b',
  user_a: 'a',
  user_b: 'b'
};
let data_obj = {}, user_obj = {};
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
         if(key.indexOf('data_')==0)
              data_obj[key]=obj[key];
         else if(key.indexOf('user_')==0)
              user_obj[key]=obj[key];
    }
}
console.log(data_obj);
console.log(user_obj);

You can use for ... in to iterate over the object's keys, then group them and their values into the new objects:

const obj = {
  data_a: 'a',
  data_b: 'b',
  user_a: 'a',
  user_b: 'b'
};
const users = {};
const data = {};

for (const k in obj) {
   if (obj.hasOwnProperty(k)) {
    if (k.startsWith("user_")) {
       users[k] = obj[k];
    } else if (k.startsWith("data_")) {
       data[k] = obj[k];
        }
   }
}

console.log(users);
console.log(data);

You can retrieve the keys of an object using

Object.keys(obj)

This will return an array of all the keys, which you can sort and use however you like.

Related