假设我有两个列表
a= ['apple', 'orange', 'banana']
b= ['red', 'orange', 'yellow']
如何使用第二个列表作为属性名称的指南将其转换为JSON对象?
例如,我会定义attributes = ['fruit', 'color']
以获得
result = [
{fruit: 'apple', color: 'red'},
{fruit: 'orange', color: 'orange'},
{fruit: 'banana', color: 'yellow'}]
答案 0 :(得分:1)
我创建了一个接受2个参数的参数,第一个是array
作为属性,第二个是array
array
作为列表项,并且它将处理属性编号多于给定的属性项:
var create = function(attrList, propertyLists) {
var result = [];
var aLen = attrList.length;
var pLen = propertyLists.length;
if (pLen === 0) {
return result;
}
var itemLength = propertyLists[0].length;
if (itemLength === 0) {
return result;
}
var i, j, obj, key;
for (i = 0; i < itemLength; ++i) {
obj = {};
for(j = 0; j < aLen; ++j) {
key = attrList[j];
if (typeof propertyLists[j] === 'undefined') {
//
continue;
}
obj[key] = propertyLists[j][i];
}
result.push(obj);
}
return result;
};
var a = ['apple', 'orange', 'banana'];
var b= ['red', 'orange', 'yellow'];
var attrs = ['fruit', 'color'];
var jsonObj = create(attrs, [a, b]);
console.log(jsonObj);
&#13;
答案 1 :(得分:0)
假设两个列表大小相同且一切都匹配,这应该可行。但是,如果它们的大小不同,则会破坏。你的数据是什么样的?
\\given
a= ['apple', 'orange', 'banana']
b= ['red', 'orange', 'yellow']
attributes = ['fruit', 'color']
\\insert this code
var result = [];
for(var i = 0; i<a.length; i++){
result.push({
attributes[0]:a[i],
attributes[1]:b[i]
});
}
console.log(result);
\\ result = [
\\ {fruit: 'apple', color: 'red'},
\\ {fruit: 'orange', color: 'orange'},
\\ {fruit: 'banana', color: 'yellow'}]
答案 2 :(得分:0)
如果您可以使用像下划线或lodash这样的库(或重新创建此处使用的方法),可以这样做:
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);