Rakesh Kumar
Rakesh Kumar

Reputation: 2855

How to convert object into array with lodash

I have below object

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

I want to convert it into below object with lodash

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

is there any way to change it. Please suggest.

Upvotes: 4

Views: 14900

Answers (2)

thefourtheye
thefourtheye

Reputation: 239653

If you want to use only lodash, then you can do it with _.mapValues and _.values to get the result, like this

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

The same can be written without the partial function, like this

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

Upvotes: 2

Amit
Amit

Reputation: 46361

This works recursively (So has to be called on the holdings property if you want to keep that) 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, ' ')));

Upvotes: 0

Related Questions