简体   繁体   中英

How to create an array of property/value from an object using Ramda?

I have an object like

const obj = {
   apple:'red',
   banana:'yellow'
}

I need to return an array with properties/values using ramda.

Example:

[
    {
        name: 'apple',
        value:'red'
    },
    {
        name: 'banana',
        value:'yellow'
    },
]

A ramda solution:

R.pipe(
  R.toPairs,
  R.map(R.zipObj(['name', 'value']))
)(obj)

You can achieve that without any 3rd party lib, with Object.entries , that returns an array with an array that contains key & value, map over it to convert it to an object.

 const obj = { apple: 'red', banana: 'yellow' }; const result = Object.entries(obj) .map(([name, value]) => ({ name, value })); console.log(result); 

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