列表到json转换的javascript [英] List to json conversion javascript

查看:113
本文介绍了列表到json转换的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表

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

如何使用第二个列表作为属性名称的指南将其转换为JSON对象?

How can I convert it to a JSON object, using a second list as a guide for the attribute names?

例如,我将定义属性= ['fruit', 'color']

For example, I would define attributes = ['fruit', 'color']

为了获得

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

推荐答案

如果您可以使用下划线或lodash之类的库(或重新创建此处使用的方法),则可以这样做:

If you can use a library like underscore or lodash (or recreate the methods used here) it can be done like so:

var attributes = ['fruit', 'color'];
var fruits = ['apple', 'orange', 'banana'];
var colors = ['red', 'orange', 'yellow'];

//Combine arrays in to list of pairs 
//(this would be expanded with each new array of attribute values)
//ORDER IS IMPORTANT
var zipped = _.zip(fruits, colors);

//Map the zipped list, returning an object based on the keys. 
//Remember the order of the arrays in the zip operation 
//must match the order of the attributes in the attributes list
var result = _.map(zipped, function(item, index) {
    return _.object(attributes, item);
});

console.log(result);

这篇关于列表到json转换的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆