What is the best way to insert an element into a JSON array at a specific index within a recurring section?

I need to include the element "delete:true" after each occurrence of "_rev" in the sample request provided below.

Original Request:

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

}

Expected Request:

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

}

After attempting the code below, I noticed that the ""_deleted" :true" is being inserted after the _rev element closes. Please take a look at the following code snippet and provide suggestions.

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"]

Answer №1

If you want to add a non-existent attribute directly and assign it a value, you can do so with the following code snippet:

#!/usr/bin/js

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

Here is the output of the example:

# js append.js 
{ docs: [ { _id: '123', _rev: '1-200' } ] }
{ docs: [ { _id: '123', _rev: '1-200', _deleted: true } ] }

You can find more detailed information in this Stack Overflow thread about adding new attributes to JSON objects using JavaScript.

It's possible that this issue has already been discussed before.

Answer №2

A more elegant solution involves using the map function along with Object.assign to avoid manually generating a string.

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

To obtain a JSON string representation, simply call JSON.stringify( output );

Check out this working example:

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);

Answer №3

let info = {
    "documents": [
        {
            "_id": "555",
            "_rev": "2-4431",
            },
        {
            "_id": "789",
            "_rev": "3-6654",
           }
         ]                         

}
let updatedData = info['documents'].map(entry => {
   entry._delete = true
   return entry
})

console.log(updatedData);

Answer №4

Have you considered adding the ._deleted attribute directly to the document? Here are a couple of ways to do it:

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

Alternatively, you can use square brackets like this:

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

Answer №5

My Solution:

     let newData = {
  items: [
    {
      _id: "123",
      _rev: "1-7836",
    },
    {
      _id: "456",
      _rev: "1-1192",
    },
  ],
};

const newArray = newData.items.map((item) => {
  item._deleted = true;
  return item;
});

console.log("UPDATED DATA>>>>>", newArray);

Updated Result:

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

}

To add an element at the beginning of the array:

newData.items[0]._deleted = true;

To add an element conditionally by ID:

let chosenId = 456;

newData.items.map((item) =>
chosenId === item._id ? (item._deleted = true) : (item._deleted = false)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Issues with Bootstrap Navbar Dropdown functionality, including flickering or unresponsiveness

While working on a project, I incorporated the FlexStart Bootstrap Template. However, I encountered an issue with the Dropdown feature on the navbar. When hovering over the menu and submenu, they flicker incessantly. Despite investing a considerable amount ...

Is it necessary to have bidirectional relationships in Sequelize?

In my database, I have two existing tables: "user" which contains columns "id" and "depId", and "department" with columns "id" and "name". The column user.depId is a foreign key referencing department.id. Now, I want to create a sequelize model for this r ...

The promise node design pattern

I'm dealing with a node issue where I need to call a Data Access Object and possibly others within it, and then render a Jade template once everything is done. Here's an example of what I want to achieve: provider1.getData(args, function(error ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

Utilize the Serde format in AWS Athena to parse and extract arrays and nested arrays present in a JSON file

In my current process, I am extracting data individually from an array and nested arrays. However, I am looking for a way to extract all data from an array with a single statement, similar to a 'SELECT *'. Here is an example of what I am currentl ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Bizarre symbols observed while extracting data from HTML tables produced by Javascript

I am in the process of extracting data from Specifically, my focus is on the "tournament-page-data-results" div within the source code. Upon inspecting the HTML source code, the data does show up, but it appears with a mix of real information and random c ...

Instructions for implementing this script in HTML and JavaScript: utilize the clone() function

I came across this code snippet here function displaytickets(){ var $panel = $('<div/>').addClass('col-xs-3 panel panel-default') $panel.append($('<div><h3 class="panel-title">Title</h3></div>&a ...

Utilizing HTML Forms in lieu of AJAX: A Beginner's Guide

Due to the Same-Origin-Policy, I am unable to use AJAX (XMLHTTPRequest). I have no access to the Server internals or the Server-Code. The Server only allows HTTPMethods: POST, OPTIONS I cannot utilize a third-party server (e.g. using curl) However, I can ...

AngularJS ngAnimate triggering prematurely

In the current setup, p2 animates in while p1 is still animating out. After that, p1 disappears and p2 glitches up the page. The desired effect is for 1 to fade out and then have 2 fade in. html: <nav> <a ng-click="changeView('p1' ...

Extracting specific data from csv or JSON files using Node.js

In my attempt to extract specific information from a csv file with multiple rows, I am using papa/babyparse to convert the data into JSON format. However, I am facing challenges in displaying/extracing particular values or columns from a designated row. v ...

Verify whether the element appears twice in the array

Is there a way to determine if an element appears more than once in an array? var arr = [elm1, elm2, elm3, elm3, elm4, elm5, elm5, elm5, elm6, elm7]; if (elm appears multiple times in the array) { // code to be executed } else { // do somethin ...

Guide to removing a colon from my JSON.stringify output

I'm encountering an issue with a JSON.stringify function. It is adding a colon after the JSON object. axios.post('http://54.196.61.131/api/v0/user/250/product/add/scan', JSON.stringify({ name: currentProduct.product. ...

How can I troubleshoot the issue of not receiving a response while attempting to upload an image using Postman with my Cloudinary-Express API?

Currently developing a backend nodejs/express API to upload image files to Cloudinary, encountering an error during testing with Postman. Below is the backend code: app.post( '/api/upload/:id', asyncHandler(async (req, res) => { try { ...

Transform this JavaScript into Vue 3 code

Hey there! I'm currently working on implementing dark mode into my project by following a tutorial. However, the tutorial is based on JavaScript and not Vue, so I'm having some trouble converting this particular section of code to work with Vue 3 ...

Generate a compilation of products developed with the help of angularjs

I have a request to make a list of items using Directives and share them through controllers. Check out my code example on plunker: Code Example Below is the JavaScript code: var app = angular.module('app', []); app.controller("BrunchesCtrl", ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...