Add a fresh item into an array in Json between existing elements

After looping through a JSON object using foreach, the output is as follows:

{"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} } 

{"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"} } 

The 'created' field in the JSON object represents a timestamp.

I am looking to add a new element in the second array based on a condition from another array. This will transform the array into:

{"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"}, "Status":{"status":"add","userid":"10"} } 

The content of

"Status":{"status":"add","userid":"10"}
will come from another JSON object.

Any assistance on accomplishing this task would be greatly appreciated.

Answer №1

If your JSON data follows this structure:

var jsonData = [
  {"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} }, 
  {"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"} } 
];

And you have another array containing an item like this:

var additionalData = {"id":"2", "Status":{"status":"add","userid":"10"} } 

To update each element in the initial jsonData with the appropriate Status from

additionalData</code, you can use the following loop:</p>

<pre><code>for (var i in jsonData) {
    if (jsonData[i].Comment.id == additionalData.id) {
        jsonData[i].Status = additionalData.Status;
    }      
}  

Now, the entry with the Comment.id of 2 has been enhanced with the corresponding Status.

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

What is the proper way to write an xpath expression in Selenium with C# to retrieve a date from a text node?

<dd> ::before <strong>Test Date:</strong> " 7/6/20 - Monday" ::after </dd> Here is a sample snippet of HTML code. I am looking to find the date that comes after the text "Test Date:". As there are multiple dates on the p ...

Wait for another user keypress event in jQuery after a 0.5 second delay

Currently, I am working on developing a live search feature for my website. In order to reduce unnecessary requests and optimize performance, I am looking to implement a simple jQuery solution (while also ensuring that there is back-end flood control in pl ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

What methods can I utilize to showcase the JSON data on my webpage efficiently?

I'm currently working on a script that makes an ajax request. The Cloud appears to be responding with JSON data, but I'm not sure how to display this data on my webpage. Any suggestions? Here you can find a link to view the neatly formatted JSON ...

Can the JSON values be arranged in order?

I have a JSON list containing country names and codes. response = '{"ContainsErrors":false,"Result":[{"Name":"Aegypten","IsoCode":"EG"},{"Name":"Aequatorialguinea","IsoCode":"GQ"},{"Name":"Aethiopien","IsoCode":"ET"},{"Name":"Afghanistan","IsoCode":" ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

How to manage nested JSON structures in Rails without using accepts_nested_attributes_for

In the process of developing a Rails application that will serve as a JSON API for a Backbone.js frontend. There are instances where we provide data in the format label: { id: 1, name: "My Label" }. When this data is used in a select box within a form (fo ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

Tips for moving a texture horizontally across a sphere using threejs

I have a 360 degree viewer tool. Is there a way to load a texture in a specific position that will rotate the original image by a certain number of degrees or units around the Y-axis without altering anything else about how the picture is displayed? If s ...

What is the best way to conceal selected options in a MUI multiselect in the select field?

I'm currently working with a MUI multiselect feature to allow for the selection of multiple options from a dropdown menu. However, I am facing an issue where I do not want the selected options to be visible within the dropdown field. Is there a way to ...

Top method for displaying and concealing GUI elements upon a click event

I would like a dat.GUI() instance to appear when a mesh is clicked, and disappear when it is clicked again. Furthermore, if it is clicked once more, I want it to reappear. Despite trying various approaches, I have been unable to achieve the desired behavio ...

Error: The Stripe webhook payload must be submitted as either a string or a Buffer

I'm currently working on setting up a subscription system using Stripe. I have mostly followed the code from their documentation, but I keep encountering the following error: Webhook signature verification failed. Webhook payload must be provided as a ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...

Exploring the capabilities of NodeJS together with the fetch function of Backbone

I have a code snippet for the front-end using fetch: var MyModel = Backbone.Model.extend(); var MyCollection = Backbone.Collection.extend({ url: '/questions', model: MyModel }); var coll = new MyCollection(); ...

I am having trouble specifying a class within an SVG using D3.js

I have been facing a strange issue with my script. When I try to execute the following code: var key="#US" d3.select(key).style("fill", "red"); it seems like it's not working for me. Interestingly, when I run the same co ...

Delete items from several arrays on a click event in React

I'm working with an array of objects that contain multiple arrays. My goal is to remove the item when a button is clicked, but I keep getting undefined as a result. JSON Data [ { "services": [ { "id": "1b9 ...

Develop a JSON structure by retrieving nested documents using Firebase Firestore and Express

I'm currently working on developing an application using Express and Firebase Cloud Functions. I'm facing a challenge in creating a nested JSON structure based on the database schema specified below: Below is the code snippet that I am using: ex ...