Home > other >  Lodash move objects under a key part of same object
Lodash move objects under a key part of same object

Time:09-28

I have an JSON object like

datas = [ 
    {"id":1,"name":"Test","age":24}, 
    {"id":2,"name":"Test1","age": 30}
]

I want to modify the JSON object like below

datas = [ 
        {"1":{"name":"Test","age":24}}, 
        {"2":{"name":"Test1","age": 30}}
    ]

I want to do the same using lodash . I can understand map over the data and create a new object should fix this

updated_data=[]
_.map datas, (data) ->
  Obj = {}
  Obj[data.id] = data
  updated_data.push(Obj) 

But I am looking for lodash way of achieving the same .

CodePudding user response:

Use Array.map() (or _.map()) with destructuring and object rest (...):

const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]

const result = datas.map(({ id, ...o }) => ({ [id]: o }))

console.log(result)

With lodash you can do the same, but instead of destructuring use _.omit() to remove the id from the original object, and use _.zipObject() combine it with the id:

const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]

const result = _.map(datas, o => _.zipObject([o.id], [ _.omit(o, 'id')]))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

CodePudding user response:

I think you don't need to use an extra library for this. This way you can achieve the desired result:

datas.map((item) => {
  const { id, ...rest } = item;
  return {
    id: rest,
  };
});
  • Related