Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

List to json conversion javascript

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...