0xPingo
0xPingo

Reputation: 2197

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: false,
  id3-field2: 0,
  id3-field3: 0,
}

And I need to make an array that looks like this:

const formatted = [
 {id: "id1", field1: true, field2: 0, field3: 3},
 {id: "id2", field1: false, field2: 1, field3: 0},
 {id: "id3", field1: false, field2: 0, field3: 0},
]

What's the best way to achieve this? This is where I'm at so far:

  1. Get the object's keys in an array
  2. Split the object keys by the hyphen
  3. Use the original keys to add in the object values

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 keys = Object.keys(response)

const split = keys.map(x => { 
  return ({"oldId": x, "id": x.split('-')[0], "key": x.split('-')[1]})
})

const splitWithValues = split.map( x => {
    let o = x;
    o.value = response[x.oldId]
    return o
})

console.log(splitWithValues)

Upvotes: 1

Views: 83

Answers (2)

Ori Drori
Ori Drori

Reputation: 191946

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);
  }, new Map()).values()];
  
console.log(result);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

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; }

Upvotes: 0

Related Questions