简体   繁体   English

如何将父字段名添加到json对象中新添加的行

[英]How to add parent fieldname to newly added row in json object

I have below code using which am able to push new row into my json object, but couldn't add parent fieldname like (d0,d1,d2.. ) into the newly added row, how can i do it? 我有下面的代码,使用它可以将新行推入json对象,但无法将父字段名(d0,d1,d2 ..)添加到新添加的行中,我该怎么办?

Code: 码:

    var d = [{
        "id": 0,
            "name": "Housing",
            "value": 71
    }, {
        "id": 1,
            "name": "Travel",
            "value": 85
    }, {
        "id": 2,
            "name": "Restaurant",
            "value": 44
    }, {
        "id": 3,
            "name": "Bank",
            "value": 33
    }];

    var dataset = {};
    d.forEach(function (e, i) {
        dataset['d' + i] = e;
    });

    alert(JSON.stringify(dataset,null,2));
    var input='Banking';

    var dataset_final={};

    d.forEach(function (e, i) {
      counter=i;
      });
      alert(counter+1);
    var input='Movies';

    d.push({id:counter+1,name:input,value:"3"});
    alert(JSON.stringify(d,null,2))

I would like to push data into 'dataset' variable directly. 我想直接将数据推送到“数据集”变量中。 How can add parent field name like 'd4' for 4th row which will be newly added for the name: Movies ? 如何为第4行添加父字段名称(如“ d4”),该名称将新添加为电影名称?

You can do something like this: 您可以执行以下操作:

var counter = Object.keys(dataset).length;
dataset['d' + counter] = {name: 'Banking', value: 100};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为新添加的行angularjs添加背景色 - How to add background color to the newly added row angularjs 如何在新添加的行(DataTables)上添加onclick事件? - How to add an onclick event on a newly added row (DataTables)? 我如何将每个字段名及其各自的值动态添加到一个 json 对象中 - how do i add each fieldname and their respective value into one json object dynamically 当我们在 React JS 中单击添加行按钮时如何自动滚动到表中新添加的行 - How to scroll to newly added row in a table automatically when we click on add row button in React JS 如何编辑来自 JSON 的新添加列表? - How to edit a newly added list from JSON? 如何向对象添加新的对象数组以使其嵌套,如果新添加的数组已存在,则向该数组添加另一个对象? - How to add a new array of objects to an object to make it nested and if newly added array already exists, add another object to that array? 在 jqGrid 中选择新添加的行 - Selecting a newly added row in jqGrid 检查所选行是否是新添加的 - check if the row selected is newly added 如何在ng-grid的第一行显示新添加的记录? - How to show newly added record in top row of ng-grid? 如何在Kendo UI网格中标记新添加的行 - How can mark newly added row in kendo ui grid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM