Skip to content Skip to sidebar Skip to footer

Convert Object Keys And Values To An Array Of Objects

I have an object that looks like this: const response = { id1-field1: true, id1-field2: 0, id1-field3: 3, id2-field1: false, id2-field2: 1, id2-field3: 0, id3-field1:

Solution 1:

Get the keys using Object#keys, and reduce them into a Map. Then spread the Map#values to get the array:

const response = {"id1-field1":true,"id1-field2":0,"id1-field3":3,"id2-field1":false,"id2-field2":1,"id2-field3":0,"id3-field1":false,"id3-field2":0,"id3-field3":0};

const result = [...Object.keys(response)
  .reduce((m, key) => {
    const [id, field] = key.split('-');
    
    const item = m.get(id) || { id };
    
    item[field] = response[key];
    
    return m.set(id, item);
  }, newMap()).values()];
  
console.log(result);

Solution 2:

You could take the parts of the key and assign the value.

var response = { 'id1-field1': true, 'id1-field2': 0, 'id1-field3': 3, 'id2-field1': false, 'id2-field2': 1, 'id2-field3': 0, 'id3-field1': false, 'id3-field2': 0, 'id3-field3': 0 },
    result = Object.keys(response).reduce(function (r, k) {
        var key = k.match(/[^-]+$/)[0],
            index = k.match(/\d+(?=-)/)[0] - 1;
        r[index] = r[index] || {};
        r[index][key] = response[k];
        return r;
    }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Convert Object Keys And Values To An Array Of Objects"