2

I am learning to use underscore js. I grouped the array. But now i need split array.

I have a grouped JSON array. For example;

var arr = [{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]}]

I want this to be the result.

var arr = [{"key" : "A", "value" : "erdem"},{"key" : "A", "value" : "metin"},{"key" : "A", "value" : "tamer"},{"key" : "A", "value" : "hüseyin"}]

I'm happy if you show me how to do it.

3
  • What did you try so far? Commented Aug 29, 2017 at 9:00
  • I could not try because I did not know what to use. If there is any simple example or auxiliary documentation I can do this, I will not hesitate to try. @MarioSantini Commented Aug 29, 2017 at 9:04
  • I think you should try with something like: _.flatten(_.map(yourArr, theSplitFunction), true); Commented Aug 29, 2017 at 9:08

3 Answers 3

2

Vanilla JS, without Underscore / lodash :

var arr = [
  {"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]},
  {"key": "B", "value": ["foo", "bar"]}
];

// create modified array of objects
var result = arr.map(item => item.value.map(v => ({ key:item.key, value:v })) );

// print result
console.log( [].concat(...result) );

Sign up to request clarification or add additional context in comments.

Comments

0

@forguta you can use this method to get your required output.

var arr = [{"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]}]
_.map(arr,function(item){ 
     var temp=[];      
     _.map(item.value, function(x){         
      temp.push({key: item.key, value: x});      
    }); 
  return temp;  
});

You can achieve the result without temp variable also (short form)

   _.map(arr,function(item){ 
      return _.map(item.value, function(x){
         return {key: item.key, value: x};
        });
    });

Comments

0

How about reduce the main array and then concat each resulting array with a initial empty array

arr.reduce((i, o)=>i.concat(o.value.map(v=>({key: o.key, value: v}))), []);

var arr = [
  {"key": "A", "value": ["erdem", "metin", "tamer", "hüseyin"]},
  {"key": "B", "value": ["foo", "bar"]}
];

var res = arr.reduce((i, o)=>i.concat(o.value.map(v=>({key: o.key, value: v}))), []);

console.log(res);

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.