将数据推送到json数组的键中

时间:2016-03-16 09:47:10

标签: javascript json

我知道这是假的问题,但我尝试了很多但是无法达到..我想将数据推入json数组但我想让函数在任何数组上工作而不设置常量键名和列..我的代码在某些数组json上工作得很好..但我不能让它适用于任何一个

function insertRow() {
  var i = 1;
  var val = document.getElementsByName("input" + i)[0].value;
  grid.data.push({"lname" : val, "fname" : val, "age" : val,"feedback" : val});
  i++;
}

不希望按名称调用密钥,并希望使其适用于任意数量的列 json数组

var json = [ {
        "lname" : "lname1",
        "fname" : "fname1",
        "age" : 10,
        "feedback" : "feedback1"
    }, {
        "lname" : "lname2",
        "fname" : "fname2",
        "age" : 90,
        "feedback" : "feedback2"
    }, {
        "lname" : "lname3",
        "name" : "fname3",
        "age" : 30,
        "feedback" : "feedback3"
    }, {
        "lname" : "lname4",
        "fname" : "fname4",
        "age" : 50,
        "feedback" : "feedback4"
    }, {
        "lname" : "lname5",
        "fname" : "fname5",
        "age" : 55,
        "feedback" : "feedback5"
    }, {
        "lname" : "lname6",
        "fname" : "fname6",
        "age" : 68,
        "feedback" : "feedback6"
    }];

1 个答案:

答案 0 :(得分:0)

我不确定,但是如果您希望计算具有不同键但具有相同值的对象以及制作此通用的对象,您可以尝试这样的事情:



function computeObject(keys, value){
  var _tmp = {};
  keys.forEach(function(k){ _tmp[k]=value;});
  return _tmp;
}

function main(){
  var k1 = ["test1", "test2", "test3"];
  var k2 = ["t1", "t2", "t3"];
  var v1 = 10;
  var v2 = "foo";
  print(computeObject(k1,v1));
  print(computeObject(k2,v2));
}

function print(obj){
  document.write("<pre>" + JSON.stringify(obj,0,4) + "</pre> <br/>");
}

main();
&#13;
&#13;
&#13;