如何在重复块中的特定索引处的json数组中添加元素?

时间:2018-01-23 11:43:56

标签: javascript arrays json object

我正在尝试添加元素"删除:true"每次出现" _rev"在下面的示例请求中提到。

原始请求:

{
    "docs": [
        {
            "_id": "123",
            "_rev": "1-7836",
            },
        {
            "_id": "456",
            "_rev": "1-1192",
           }
         ]                         

}

预期请求:

{
    "docs": [
        {
            "_id": "123",
            "_rev": "1-7836",
            "_deleted" :true
            },
        {
            "_id": "456",
            "_rev": "1-1192",
            "_deleted" :true
           }
         ]                         

}

当我尝试以下代码时,"" _deleted" :真"在-rev元素关闭后插入。 PFB也是如此并建议。

function main(params) {
for (var i = 0; i< params.docs.length; i++) {
for (var value in params.docs[i]) {
if(value == '_rev'  && params.docs[i]._rev ){ 
var string1 = JSON.stringify(params.docs[i]);
var str = ',';
var string2 = '"';
var string3 =str+string2+ '_deleted'+ string2+ ':' + "true" ;
var res =  string1 + string3  ;
}
}
}
}
  ######################
[
  "2018-01-23T09:44:23.568738362Z stdout:
  {\"_id\":\"123\",
  \"_rev\":\"1-7836\"},
  \"_deleted\":true"]

4 个答案:

答案 0 :(得分:0)

使用mapObject.assign代替生成字符串

var output = params.docs.map( s => Object.assign( {}, {"_deleted" :true}, s ) );

然后,您可以使用JSON.stringify( output );

将其转换为字符串

<强>演示

var params = {
  "docs": [{
      "_id": "123",
      "_rev": "1-7836",
    },
    {
      "_id": "456",
      "_rev": "1-1192",
    }
  ]
};
var output = params.docs.map(s => Object.assign({}, {
  "_deleted": true
}, s));
console.log(output);

答案 1 :(得分:0)

var data = {
    "docs": [
        {
            "_id": "123",
            "_rev": "1-7836",
            },
        {
            "_id": "456",
            "_rev": "1-1192",
           }
         ]                         

}
var newData = data['docs'].map(item => {
   item._delete = true
   return item
})

console.log(newData);

答案 2 :(得分:0)

为什么不简单地将._deleted属性放到doc中,就像这样?

function main(params) {
  for (var i = 0; i< params.docs.length; i++) {
    params.docs[i]._deleted = true;
    var res = JSON.stringify(params.docs[i]);
  }
 }
}

或者像这样:

function main(params) {
  for (var i = 0; i< params.docs.length; i++) {
    params.docs[i]["_deleted"] = true;
    var res = JSON.stringify(params.docs[i]);
  }
 }
}

答案 3 :(得分:0)

您可以直接引用not existing属性并指定一个值:

<div class="my-custom-select error">

示例输出:

#!/usr/bin/js

var myJSON = { "docs": [ { "_id":"123", "_rev":"1-200" } ] }
console.log(myJSON);
myJSON.docs[0]["_deleted"]=true;
console.log(myJSON);

在此处阅读更广泛的示例:Add new attribute (element) to JSON object using JavaScript

所以这可能是重复......