2

Is there an easy way to go from an object to multiple objects? From this:

var obj = { 'generics.type': 'search.type', 'wood.name': 'search.name' }

to this:

var nestedObj = [ {'generics.type': 'search.type'}, {'wood.name': 'search.name'} ]

essentially the reverse of lodash defaults: https://lodash.com/docs/4.17.4#defaults

Been looking for this for hours, and now I'm turning here... Thanks

3
  • Is 'nestedObj` supposed to be an array? Commented Feb 2, 2017 at 14:53
  • Whatever you are trying to do, I can't see how it's the inverse of _.defaults. Commented Feb 2, 2017 at 17:06
  • Yes it was supposed to be an array. forgot to mention. Have edited question Commented Feb 2, 2017 at 18:34

5 Answers 5

2

With lodash or underscore you could use map:

var result = _.map(obj, (v,k) => ({[k]: v}));
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe you want something shorter, but I think the obvious solution is the only one.

var obj = { 'generics.type': 'search.type', 'wood.name': 'search.name' };
var arr = _.map(obj, function(v, k) { var o = {}; o[k] = v; return o; });
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Comments

1

Try this:

var createDiffObjs = function(obj ){
    var nestedObj = [];
    for( var prop in obj ) {
                 var elem = {};
                 elem[ prop ] = obj [prop ];
                 nestedObj.push( elem );
                }
    return nestedObj;
}

And then use it thus:

nestedObj = createDiffObjs( obj ); 

1 Comment

I think you'll find that doesn't work - you can't use a variable as the key in a literal object
0

First of all check your object structure is valid or not with http://pro.jsonlint.com/

And then go to investigate ES2015=ES6 new JavaScript specifications which calls Destructuring of arrays(i.e. objects) https://babeljs.io/learn-es2015/ you will find everything about new approach on JavaScript. Good Luck!!! (if your object structure would be right we could help you)

Comments

0
var nestedObj = { {'generics.type': 'search.type'}, {'wood.name': 'search.name'} }

This is not a valid data structure in JavaScript. A JavaScript object is a pair of key and value.

Use an array instead for multiple objects:

var multipleObjs = [ {'generics.type': 'search.type'}, {'wood.name': 'search.name'} ]

1 Comment

I found out. Thanks Mia. I am looking for a way (simple/easy) to convert it into an array with nested objects. Have edited the question...

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.