Search code examples
jsonloopsobjectecmascript-6key

replacing key object for the array values


Im having a problem with replacing keys in object

let headers = ['title1', 'title2', 'title3']

let obj = {
    0: ['name1', 'name2, 'name3],
    1: ['example1', 'example2, 'example3],
    2: ['xx', 'yy, 'zz],
}

What I'm trying to do is:

let obj = {
   'title1': ['name1', 'name2, 'name3],
   'title2': ['example1', 'example2, 'example3],
   'title3': ['xx', 'yy, 'zz],
}

I'm not sure if my approach is correct:

  Object.keys(obj).map((el, index, arr) => {
      headers.forEach((item, item_index) => {
          arr[item_index] = item
      })
  })

When I console.log(Object.keys(obj)) I'm still getting: 0,1,2 ....


Solution

  • Object.values returns only values from specified obj and Object.fromEntries allows you to create a new object based on two-element list of arrays:

    let headers = ['title1', 'title2', 'title3'];
    
    let obj = {
        0: ['name1', 'name2', 'name3'],
        1: ['example1', 'example2', 'example3'],
        2: ['xx', 'yy', 'zz']
    };
    
    let result = Object.fromEntries(Object.values(obj).map((v,i) => ([headers[i], v])));
    console.log(result);