简体   繁体   中英

Convert object to array of objects using lodash 3

how can i convert an object like this

{
  "ID_PROC_GD": "1",
  "DT_INI": "2018-06-06",
  "CD_GD": "1",
  "DT_INI_GD": "2018-05-28",
  ...
}

to this

[
  {
    "name": "DT_INI",
    "value": "2018-06-06"
  },
 ...
]

I am using lodash 3.10.1

map always returns array type, and you can use both value and key in iterator:

_.map(obj, (value, name) => ({name, value}))

 const obj = { "ID_PROC_GD": "1", "DT_INI": "2018-06-06", "CD_GD": "1", "DT_INI_GD": "2018-05-28", } const result = _.map(obj, (value, name) => ({ name, value })) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script> 

You can use Object.entries() and array#map .

 let data = { "ID_PROC_GD": "1", "DT_INI": "2018-06-06", "CD_GD": "1", "DT_INI_GD": "2018-05-28"}, result = Object.entries(data).map(([name, value]) => ({name, value})); console.log(result); 

You can use map

 let data = { "ID_PROC_GD": "1", "DT_INI": "2018-06-06", "CD_GD": "1", "DT_INI_GD": "2018-05-28"}, result = _.map(data, (value, name) => ({name, value})); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script> 

 let obj = {
  "ID_PROC_GD": "1",
  "DT_INI": "2018-06-06",
  "CD_GD": "1",
  "DT_INI_GD": "2018-05-28" 
}

function getNameValObj(ele) {
  return {name: ele, value:obj[ele]};
}
 
let objList = _.flatMap(Object.keys(obj), getNameValObj);

You can try this:

let obj={
  "ID_PROC_GD": "1",
  "DT_INI": "2018-06-06",
  "CD_GD": "1",
  "DT_INI_GD": "2018-05-28",
}
_.map(obj,(item,index)=>({
    ['name']:index,
    ['value']:item
}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM