Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have two lists

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

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

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

in order to get

result = [
  {fruit: 'apple', color: 'red'}, 
  {fruit: 'orange', color: 'orange'}, 
  {fruit: 'banana', color: 'yellow'}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

I've create one that accept 2 arguments, first is array as attributes, second is array of array as list items, and it'll handle if attribute number is more then given property items:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...