如何使用nodejs

时间:2018-02-26 09:21:59

标签: javascript arrays json node.js

我有这个寻求阵列

{
  "arr": [
    {
      "obj": [
        {
          "reg_at": 1519615460064,
          "id": "367790083"
        },
        {
          "reg_at": 1519615460064,
          "id": "41370460"
        }
      ]
    },
    {
      "obj": [
        {
          "reg_at": 1519615460065,
          "id": "215109021"
        },
        {
          "reg_at": 1519615460065,
          "id": "72173002"
        }
      ]
    }
  ]
}

我希望将所有id对象分成如下数组:

[367790083, 41370460, 41370460]

请问我如何使用nodejs实现这一目标?我试过循环,但没有得到所需的输出。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

使用reducemap

var output = obj.arr.reduce( (a, c) => 
    a.concat( c.obj.map(  
       s => +s.id )  )  , [])

<强>解释

  • 使用reduce 迭代并累积输出到a
  • 使用map返回obj
  • arr数组中每个项目的ID(转换后的数字

<强>演示

var obj = {
  "arr": [
    {
      "obj": [
        {
          "reg_at": 1519615460064,
          "id": "367790083"
        },
        {
          "reg_at": 1519615460064,
          "id": "41370460"
        }
      ]
    },
    {
      "obj": [
        {
          "reg_at": 1519615460065,
          "id": "215109021"
        },
        {
          "reg_at": 1519615460065,
          "id": "72173002"
        }
      ]
    }
  ]
};
var output = obj.arr.reduce( (a, c) => 
    a.concat( c.obj.map(  
       s => +s.id )  )  , []);
console.log( output );

答案 1 :(得分:2)

看到你是一个初学者,我会用这种老式的方式来理解数据的组织方式。

var data = {
  "arr": [
    {
      "obj": [
        {
          "reg_at": 1519615460064,
          "id": "367790083"
        },
        {
          "reg_at": 1519615460064,
          "id": "41370460"
        }
      ]
    },
    {
      "obj": [
        {
          "reg_at": 1519615460065,
          "id": "215109021"
        },
        {
          "reg_at": 1519615460065,
          "id": "72173002"
        }
      ]
    }
  ]
};

// The variable for the result
var result = [];

// "data" is the object and "arr" is an array and has a length
for (var i=0; i<data.arr.length; i++) {
    // For clarity, pick the current object from the array
    var theArrItem = data.arr[i];

    // That object then has a "obj" which is an array
    for (var j=0; j<theArrItem.obj.length; j++) {
        // Again, pick the current object
        var theObjItem = theArrItem.obj[j];
        // Add the id of the current object to the result
        result.push(theObjItem.id);
    }
}

console.log(result);