How to convert object to array with lodash

I have an object

{
    "holdings": [
        {
            "label": "International",
            "value": 6
        },
        {
            "label": "Federal",
            "value": 4
        },
        {
            "label": "Provincial",
            "value": 7
        }
    ]
}

      

I want to convert it to below object with lodash

{
    "holdings": [
        [
            "International",
            6
        ],
        [
            "Federal",
            4
        ],
        [
            "Provincial",
            7
        ],
        [
            "Corporate",
            7
        ]
    ]
}

      

is there any way to change it. Please suggest.

+3


source to share


2 answers


If you only want to use lodash, you can do so with _.mapValues

and _.values

to get the result, for example

console.log(_.mapValues(data, _.partial(_.map, _, _.values)));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }

      



The same can be written without a partial function, for example

console.log(_.mapValues(data, function(currentArray) {
    return _.map(currentArray, _.values)
}));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }

      

+1


source


This works recursively (so you need to call the property holdings

if you want to store it) and "understands" nested objects and nested arrays. (vanilla JS):



var source = {
    "holdings": [
        {
            "label": "International",
            "value": 6
        },
        {
            "label": "Federal",
            "value": 4
        },
        {
            "label": "Provincial",
            "value": 7
        }
    ]
}

function ObjToArray(obj) {
  var arr = obj instanceof Array;

  return (arr ? obj : Object.keys(obj)).map(function(i) {
    var val = arr ? i : obj[i];
    if(typeof val === 'object')
      return ObjToArray(val);
    else
      return val;
  });
}

alert(JSON.stringify(ObjToArray(source.holdings, ' ')));
      

Run codeHide result


0


source







All Articles