-4

I will go straight to the point, so here is what I have:

    const someObj = {
    one: [
        {
            id: 123,
            text: "lalala"
        },
        {
            id: 456,
            text: "lalala2"
        },
        {
            id: 789,
            text: "lalala3"
        }
    ],
    two: [
        {
            id: 111,
            text: "text random"
        },
        {
            id: 222,
            text: "text random2"
        },
        {
            id: 333,
            text: "text random3"
        }
    ]
};

and this is what I need to have:

    const someOtherObj = {
    111: {
        id: 111,
            text: "text random"
    },
    222: {
        id: 222,
        text: "text random2"
    },
    333: {
        id: 333,
        text: "text random3"
    },
    123: {
        id: 123,
        text: "lalala"
    },
    456: {
        id: 456,
        text: "lalala2"
    },
    789: {
        id: 789,
        text: "lalala3"
    }
};

I know this can be achieved without million loops, just I can't think of any smart solution. :/ So, maybe someone can help me to solve this puzzle? :)

Thanks :)

tdk
  • 151
  • 3
  • 10
  • There are several hundred posts on Stack Overflow alone about how to flatten arrays and objects. Why don't you try something, then come to us with a specific question on where you got stuck? – Heretic Monkey Jul 13 '17 at 13:09

2 Answers2

0

Try with Array#reduce function with ES6

  1. first reduce created array with all inner Object
  2. Second reduce used to create object key with id

const someObj = { one: [ { id: 123, text: "lalala" }, { id: 456, text: "lalala2" }, { id: 789, text: "lalala3" } ], two: [ { id: 111, text: "text random" }, { id: 222, text: "text random2" }, { id: 333, text: "text random3" } ] };

var res = Object.values(someObj).reduce((a,b)=> (b.forEach(val=> a.push(val)),a),[])

var f = res.reduce((a,b)=> (a[b.id] = b, a),{})
console.log(f)
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

You only need to use two loops, no more (using ES6 seeing that your example used it as well)

const newObj = {};
for(const key in someObj) {
  for(let i = 0; i < someObj[key].length; i++) {
    const obj = someObj[key][i];
    newObj[obj.id] = {
      id: obj.id,
      text: obj.text
    }
  }
}
Max K
  • 656
  • 1
  • 6
  • 22