Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like:

{
    "all": [
        {
            "image":{
                "URL":"img/img1.jpeg",
                "font": "sfsdfsdf",
                "color": "sfsdfs"
            },
            "music": {
                "URL":"fsfsfd",
                "time": {
                    "start":"sfsdf",
                    "end":"qdqsd"
                }
            }
        },
        {
            "image":{
                "URL":"img/img2.jpeg",
                "font": "sfsdfsdf",
                "color": "sfsdfs"
            },
            "music": {
                "URL":"fsfsfd",
                "time": {
                    "start":"sfsdf",
                    "end":"qdqsd"
                }
            }
        }
    ]
}

I also have a second array that contains the path split into segments for the key I want to update, as shown below:

var path = ["all", 0, "image", "font"]

Currently, I am iterating through the path variable and checking if the key exists in my JSON data. However, I am unsure how to update the JSON array without changing its structure...

For instance, I would like to change the value of myArray[all][0][image][font] to "My Other Value"

The ultimate objective is to update my JSON array and save the changes to a JSON file.

EDIT :

I have discovered a solution from this resource : Dynamically updating a JavaScript object from a string path

Answer №1

Let's start by clarifying that this solution does not involve jQuery.

Instead, a convenient approach is to utilize the _.get() function provided by Lodash. It perfectly aligns with your requirements.

Certainly, you could implement this functionality yourself with relatively straightforward code. However, Lodash offers an array of reliable utility functions, making it beneficial to become acquainted with them. Below is an example:

let data = {
    "all": [
        {
            "image":{
                "URL":"img/img1.jpeg",
                "font": "sfsdfsdf",
                "color": "sfsdfs"
            },
            "music": {
                "URL":"fsfsfd",
                "time": {
                    "start":"sfsdf",
                    "end":"qdqsd"
                }
            }
        },
        {
            "image":{
                "URL":"img/img2.jpeg",
                "font": "sfsdfsdf",
                "color": "sfsdfs"
            },
            "music": {
                "URL":"fsfsfd",
                "time": {
                    "start":"sfsdf",
                    "end":"qdqsd"
                }
            }
        }
    ]
};

let path = [ "all", 0, "image", "font" ];

let value = _.get( data, path );

console.log( value );
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba7a4afaab8a38bffe5fafce5fafb">[email protected]</a>/lodash.min.js"></script>

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

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

How can an array of objects be sent as a query string to the endpoint URL in React?

I'm currently developing a react application and facing the challenge of dynamically constructing and appending query strings to URLs. This is necessary because I have a shared base endpoint for all links, but each link may require different parameter ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

Developing a Python loop to mimic a "goto" style solution

My approach involves simulating a goto sequence. Is there a more elegant solution available? Note: The concept of storing the variables in a class variable was just for amusement (due to the .format() accessing story). n=0 while n==0: print("What is ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

What is the best way to display only the host and pathname of the links generated by Array.map()?

I am currently utilizing Array.map() to display a list of files in cache: <div data-offline></div> <script> var version = 'v1:'; if (navigator && navigator.serviceWorker) { caches.open(versio ...

Converting Json Array to CSV using PHP

I have an array of providers [ { "reference":"01042", "images": [ "http:\/\/static1.provider.com\/34\/01042.jpg" ] }, { "reference":"01057", "images":[ "http ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Tool that closely mirrors the functionalities of Google Maps

Seeking to develop an interactive image feature on my website akin to Google Maps but with custom images. Desiring functionalities like drag, scroll, and zoom in/out for enhanced user experience. Interested in any suggested tools or plugins for this purp ...

Implementing file uploads using AJAX in CodeIgniter will continue to run, even if the value is null or undefined

I need to trigger another ajax request if the file has not been input yet. However, it is currently still carrying out the form action. Below is my view code: <form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/&ap ...

When hovering, apply style 1 to all elements with the same id, and style 2 to the hovered element

I'm working with some user-generated divs that I want to dynamically highlight when hovered over, while simultaneously blurring the other divs. My challenge is figuring out how to change the style of the hovered div separately from all the others. Th ...

Manage and preserve your node.js/express sessions with this offer

Currently, I am working on a web application that encounters an issue where every time fs.mkdir is called, all the current express sessions are deleted. This causes me to lose all session data and I need a solution to keep these sessions intact. I have att ...

Avoid having Vue CLI delete all files in the dist folder

As I work on my Vue project, I am facing a challenge in syncing the dist folder with Git. Previously, this process ran smoothly when using webpack. However, after transitioning to @vue/cli and creating my project with vue create myProject instead of vue in ...

Leveraging the power of a JavaScript framework within the script tag

Hello there! I'm just starting out with vue.js and exploring different JavaScript frameworks. Recently, I came across an interesting example based on the documentation. import modal from 'vue-semantic-modal' export default { components ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Troubleshooting: Why isn't my Ajax post functioning correctly with PHP variables?

After researching similar questions, I have discovered that in order to send a JavaScript value to a PHP variable, AJAX must be used. Here is what I have tried: function onCursorChanged(e, data) { $.post('familytree.php', {id: data.context.i ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...