如何将带有数组的JSON对象拆分为单独的对象

时间:2016-11-25 06:26:31

标签: javascript json

我有以下格式的JSON:

{
    "line_items": [
        {
            "rate": ["10", "20"],
            "description": ["desc 1", "desc 2"],
            "name": ["name 1", "name 2"]
        }
    ]
}

数组中元素的数量可能会有所不同,但每个元素的数组总是彼此相同。我通过将对象分成多个对象来删除数组。

像这样:

{
    "line_items": [
        {
            "rate": "10",
            "description": "desc 1",
            "name": "name 1"
        },
        {
            "rate": "20",
            "description": "desc 2",
            "name": "name 2"
        }
    ]
}

我需要使用javascript执行此操作。

是否有能为我这样做的功能?我想我可能不得不使用foreach循环,但不知道如何处理它。

8 个答案:

答案 0 :(得分:0)



var obj = {
    "line_items": [
        {
            "rate": ["10", "20"],
            "description": ["desc 1", "desc 2"],
            "name": ["name 1", "name 2"]
        }
    ]
}

var props = [];
for (var key in obj.line_items[0]) {
  props.push(key);
}

var arrD = [];

obj.line_items[0].rate.forEach(function(ele,ind){
var temp = {};
 props.forEach(function(innerEle){
   temp[innerEle] = obj.line_items[0][innerEle][ind];
 });
 arrD.push(temp);
});
var obj = {"line_items" : arrD}
console.log(obj);




 obj.line_items[0].rate.forEach(function(ele,ind){
   var temp = {};
   props.forEach(function(innerEle){
     temp[innerEle] = obj.line_items[0][innerEle][ind];
   });
  arrD.push(temp);
 });

答案 1 :(得分:0)

这应该有效

function itemExpander(json) {
  var result = {line_items: []};
  var item = json.line_items[0]

  for (var i = 0; i < item.rate.length; i++) {
    result.line_items.push({
      rate: item.rate[i],
      description: item.description[i],
      name: item.name[i],
    })
  }

  return result;
}

答案 2 :(得分:0)

使用它

var obj = {
    "line_items": [
        {
            "rate": ["10", "20"],
            "description": ["desc 1", "desc 2"],
            "name": ["name 1", "name 2"]
        }
    ]
};

length = obj.line_items[0].rate.length;

newObject ={};
var limits = [];

for(var i=0; i < length ; i++){
          newObject["rate"] = obj.line_items[0].rate[i];
          newObject["description"]= obj.line_items[0].description[i];
          newObject["name"]=obj.line_items[0].name[i];
          limits.push(newObject);
          newObject ={}
     }

var lastObject = {"line_items":limits};
console.log(lastObject);

答案 3 :(得分:0)

递归就地方法:

var object = {
    "line_items": [
        {
            "rate": ["10", "20"],
            "description": ["desc 1", "desc 2"],
            "name": ["name 1", "name 2"]
        }
    ]
};

function oneIntoMany(list) {
    var obj = list[0];
    var tmp_obj = {};
    var again = true;
    for(var prop in obj){
        if(obj.hasOwnProperty(prop)){
            if(obj[prop].length > 1){
                tmp_obj[prop] = obj[prop].pop();
            }else{
                obj[prop] = obj[prop][0];
                again = false;
            }
        }
    }
    if(again){
        list.push(tmp_obj);
        oneIntoMany(list);
    }
}

oneIntoMany(object.line_items);
console.log(object);

答案 4 :(得分:0)

这是一个有效的解决方案。希望它有所帮助!

var obj = {
    "line_items": [
        {
            "rate": ["10", "20"],
            "description": ["desc 1", "desc 2"],
            "name": ["name 1", "name 2"]
        }
    ]
}

var arr1 = [];
var arr2 = [];
var arr3 = [];
var result = {line_items: []};

for(var i in obj){
  for(var j in obj[i]){
    var myObject = obj[i];
     if(myObject[j].hasOwnProperty("rate") && myObject[j].hasOwnProperty("description") && myObject[j].hasOwnProperty("name")){
     arr1 = myObject[j]["rate"];
     arr2 = myObject[j]["description"];
     arr3 = myObject[j]["name"];
    }
  }
}

for(var k = 0; k < 2; k++){
      result.line_items.push({
      rate: arr1[k],
      description: arr2[k],
      name: arr3[k]
    })
}
console.log(result);

答案 5 :(得分:0)

    var data = {
        "rate": ["10", "20"],
        "description": ["desc 1", "desc 2"],
        "name": ["name 1", "name 2"]
       }


    function lengthChecker(items){
        for(var i in items){
            return items[i].length;
        }
    }

    function processFunc(items){
        var keys = Object.keys(items);
        var arr = [];
        var length = lengthChecker(items)
        for(let i=0 ; i < length ; i++){
            let cell = {};
            for(var j in keys){
                let targetKeyName = keys[j];
                cell[targetKeyName] = items[targetKeyName][i];
            }
            arr.push(cell);
        }

        return arr;
    }

    var processData = processFunc(data)
    console.log('processData',processData)

答案 6 :(得分:0)

您可以迭代所有属性和数组,并使用单个属性构建一个新数组。

&#13;
&#13;
var data = { line_items: [{ rate: ["10", "20"], description: ["desc 1", "desc 2"], name: ["name 1", "name 2"] }] },
    result = { line_items: [] };

data.line_items.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a, i) {
            result.line_items[i] = result.line_items[i] || {};
            result.line_items[i][k] = a;
        });
    });
});

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

line_items中包含更多项目的版本。

&#13;
&#13;
var data = { line_items: [{ rate: ["10", "20"], description: ["desc 1", "desc 2"], name: ["name 1", "name 2"] }, { rate: ["30", "40"], description: ["desc 3", "desc 4"], name: ["name 3", "name 4"] }] },
    result = { line_items: [] };

data.line_items.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a, i) {
            result.line_items[this.count + i] = result.line_items[this.count + i] || {};
            result.line_items[this.count + i][k] = a;
        }, this);
        this.max = Math.max(this.max, o[k].length);
    }, this);
    this.count += this.max;
    this.max = 0;
}, { count: 0, max: 0 });

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 7 :(得分:0)

  
    

将您的对象插入问题变量,请参阅以下代码。 line_items对象可以包含多个元素。

  
var question={
    "line_items": [
        {
            "rate": ["10", "20","30"],
            "description": ["desc 1", "desc 2","desc 3"],
            "name": ["name 1", "name 2" ,"desc 3"]
        }
    ]
};
var answer={"line_items":[]};
for(var i=0;i<question['line_items'].length;i++){
    for(var j=0;j<question['line_items'][i]['rate'].length;j++){
        var newObject={};
        newObject['rate']=question['line_items'][i]['rate'][j];
        newObject['description']=question['line_items'][i]['description'][j];
        newObject['name']=question['line_items'][i]['name'][j];
        answer["line_items"].push(newObject);
    }
}