1

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)

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Wow that was fast ! Thank you !
Refinement to match expected results const item = m.get(id) || {id:id};//missing id prop
Hello, can you provide code with JavaScript functionality without new features?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.