4

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.

3
  • does it need to be with lodash? Commented Jul 22, 2015 at 11:05
  • yes...but suggest if you have any better solution Commented Jul 22, 2015 at 11:06
  • 1
    holdings.map(function(l){return Object.keys(l).map(function(v){return l[v]})}) Commented Jul 22, 2015 at 11:19

2 Answers 2

2

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 ] ] }
Sign up to request clarification or add additional context in comments.

Comments

0

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, ' ')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.