Javascript数组操作 - 复杂的JSON响应

时间:2016-05-31 01:14:43

标签: javascript jquery json

示例对象数组由服务器发送 -

var x = [{a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
    {a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
    {a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]}];

如何改变它,看起来像这样 -

var y = [{a:1,b:2,c:3,h:8},{f:6,g:7,h:8},
     {a:1,b:2,c:3,h:8},{f:6,g:7,h:8},
     {a:1,b:2,c:3,h:8},{f:6,g:7,h:8}];

我刚才尝试过这个丑陋的代码 -

function arrange(arr){
 var temp1 = [];
 var temp2 = [];
 var output = [];

   for(var i = 0;i < arr.length;i++){
     temp1 = arr[i].d;
     temp2 = arr[i].e;
     temp1.push(temp2[0].h);

     output.push(arr[i].a,arr[i].b,arr[i].c,temp2[0].h);
     output.push(temp1);

     return output;
  }
}

输出错误,只给出了值,我需要键/值对。

我想向View发送正确的回复。我现在在一份不同的工作中工作,学习编程就是我的一面。现在,我被卡住了。请原谅可怕的代码:)。

3 个答案:

答案 0 :(得分:1)

Javascript明确提供了解构表达式:将数据提取到所需对象的非常简洁的方法。

let result = x.reduce((elts, {a, b, c, d: [{f, g}], e: [{h}]}) => {
  return elts.concat({a, b, c, h}, {f, g, h})
}, [])

如果您console.log变量result,您会发现它在y中提供了您想要的值:

[{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8},{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8},{"a":1,"b":2,"c":3,"h":8},{"f":6,"g":7,"h":8}]

答案 1 :(得分:0)

您正在创建数组。你想要创建对象。

output = [];
for(var i = 0;i < arr.length;i++){
    var obj = {
        a: arr[i].a,
        b: arr[i].b,
        c: arr[i].c,
        h: arr[i].e.h
    }

    var obj2 = {
        f: arr[i].d.f,
        g: arr[i].d.g,
        h: arr[i].e.h
    }


    output.push(obj);
    output.push(obj2);
}
return output;

答案 2 :(得分:0)

试试这个。对您的尝试所做的更改进行了评论:

var x = [{a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
    {a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]},
    {a:1,b:2,c:3,d:[{f:6,g:7}],e:[{h:8}]}];

function arrange(arr){
  var temp1, temp2, output = [];

  for(var i = 0;i < arr.length;i++){
    temp1 = arr[i].d[0]; // grab first array element
    delete arr[i].d;     // delete d from object
    temp2 = arr[i].e[0]; // grab first array element
    delete arr[i].e;     // delete e from object

    output.push($.extend(arr[i], temp2)); // merge object and e, push
    output.push($.extend(temp1, temp2));  // merge d and e, push
  }
  return output; // move from in for loop to here
}

输出:

[
  {a:1,b:2,c:3,h:8}, {f:6,g:7,h:8}, 
  {a:1,b:2,c:3,h:8}, {f:6,g:7,h:8}, 
  {a:1,b:2,c:3,h:8}, {f:6,g:7,h:8}
]

JSBin example.

您标记了jQuery,因此它用于extend函数。没有使用jQuery的人可以使用Plain JS或更小的库。