2015-07-07 3 views
-1

Скажем, у меня есть два спискаСписок для преобразования JavaScript формата JSON

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

Как я могу преобразовать его в объект JSON, используя второй список в качестве руководства для имен атрибутов?

К примеру, я бы определить атрибуты = ['fruit', 'color']

для того, чтобы получить

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

ответ

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); 
+0

Это хорошо работает! Благодаря! – dksakkos

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'}] 
+0

Вы должны инициализировать результат с помощью инструкции var/let, чтобы избежать создания глобального. 'var result = [];' – ecarrizo

+0

@ecarrizo вы правы, исправил его. Спасибо – 2016rshah

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);

Смежные вопросы