将多个对象附加到单个数组中

时间:2017-09-14 06:48:06

标签: javascript arrays

我有一个结构对象数组来自迭代数组对象的服务器响应,如样本

array[1] ={
    "ID": "123",
    "Name": "John",
    "Age": "15"     
}
array[2] ={
    "ID": "456",
    "Name": "Sue",
    "Age": "18"     
}
array[n] ={

}

但是现在我想追加数组值,如果条件年龄低于18,则在以下结构中作为上述数组的迭代值 预期产出:

{
    "Stud": [{
        "ID": "123",
        "Name": "John",
        "Age": "15"
    }, {
        "ID": "456",
        "Name": "Sue",
        "Age": "18"
    },{n........
  }]
}

4 个答案:

答案 0 :(得分:1)

var output = { "Stud" : [] };
for (var i = array.length - 1; i >= 0; i--) {
    if (array[i].Age < 18) {
        output.Stud.push(array[i]);
    }
}
console.log(output);

答案 1 :(得分:0)

简单地

var output = { "Stud" : array }; //existing 'array'

答案 2 :(得分:0)

您可以使用function code() { var leer = document.getElementById('1').value, array = []; //debugger; for (var i = 0; i < leer.length; i++) { array[i] = leer[i].charCodeAt(0); } document.getElementById('2').innerHTML = 'Chale, chale ' + array.join(''); } function decode() { var leer = document.getElementById('1').value, array = []; //debugger; for (var i = 0, char; char = leer[i]; i++) { array[i] = String.fromCharCode(leer[i].charCodeAt(0)); } document.getElementById('2').innerHTML = 'Chale, chale ' + array.join(''); }选择年龄小于或等于18的对象。

&#13;
&#13;
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="exCSS.css">
</head>

<body>
<form>
  Escriba el Mensaje:<br><br>
  <input type="text" id="1" />      
  <br><br> Elige una opción:
  <br><br>
  <input type="button" name="cifra" value="Cifrar" onclick="code()">
  <input type="button" name="decifra" value="Decifrar" onclick="decode()">
  <br><br>
  <textarea id="2" rows="5" cols="40"></textarea>
</form>
</body>
</html>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

简单地迭代并检查年龄是否< 18或不。如果是这样推动到另一个阵列。

    var array = [];
    var array_below_18 = [];
    array[0] ={
        "ID": "123",
        "Name": "John",
        "Age": "15"     
    }
    array[1] ={
        "ID": "456",
        "Name": "Sue",
        "Age": "18"     
    }

    array[1] ={
        "ID": "456",
        "Name": "Sue",
        "Age": "14"     
    }

    for(i=0;i<array.length;++i){
       if(parseInt(array[i].Age)<18){
          array_below_18.push(array[i]);
       }
    }

    var final_object = {
        "Stud" : array_below_18
    }

    console.log(final_object);