List to json conversion javascript -


let's have 2 lists

a= ['apple', 'orange', 'banana'] b= ['red', 'orange', 'yellow'] 

how can convert json object, using second list guide attribute names?

for example, define attributes = ['fruit', 'color']

in order get

result = [   {fruit: 'apple', color: 'red'},    {fruit: 'orange', color: 'orange'},    {fruit: 'banana', color: 'yellow'}] 

if can use library underscore or lodash (or recreate methods used here) can done so:

var attributes = ['fruit', 'color']; var fruits = ['apple', 'orange', 'banana']; var colors = ['red', 'orange', 'yellow'];  //combine arrays in list of pairs  //(this expanded each new array of attribute values) //order important var zipped = _.zip(fruits, colors);  //map zipped list, returning object based on keys.  //remember order of arrays in zip operation  //must match order of attributes in attributes list var result = _.map(zipped, function(item, index) {     return _.object(attributes, item); });  console.log(result); 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -