Changing the key of a nested item within an array of objects using JavaScript

My task in JavaScript is to change the names of canBook -> quantity, variationsEN -> variations, and nested keys valueEN -> value.

var prod = [{
    price: 10,
    canBook: 1
}, {
    price: 11,
    canBook: 2,
    variationsEN: [{
        valueEN: 1
    }, {
        valueEN: 2
    }]
}]

I have successfully renamed the main keys, but I am struggling with changing the nested ones like valueEN.

prod.map(p => ({
    quantity: p.canBook, variations:p.variationsEN
}))

Answer №1

To repeat the same technique, follow these steps:

variations:p.variationsEN

should be replaced with:

variations:(p.variationsEN || []).map(q => ({ value: q.valueEN }))

If the property does not exist in your source object, the additional || [] ensures that an empty array is generated for it.

Answer №2

One way to tackle this is by using a recursive method that utilizes an object to map the properties and create new objects or arrays.

function propertyRenamer(value) {
    if (!value || typeof value !== 'object') return value;
    if (Array.isArray(value)) return value.map(propertyRenamer);
    return Object.fromEntries(Object
        .entries(value)
        .map(([k, v]) => [propertyMap[k] || k, propertyRenamer(v)])
    );
}

var propertyMap = { canBook: 'quantity', variationsEN: 'variations', valueEN: 'value' },
    products = [{ price: 10, canBook: 1 }, { price: 11, canBook: 2, variationsEN: [{ valueEN: 1 }, { valueEN: 2 }] }],
    renamedResult = propertyRenamer(products);

console.log(renamedResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

When dealing with JSON data received from a server, you can utilize a reviver function to handle the structure in a specific way:

var product = JSON.parse(productJSON, function (key, value) {
 if (key === "canBook") {
   this["quantity"] = value;
 } else {
   return value;
 }
});

(In scenarios where you are working with a JavaScript Object instead of a JSON string, it is advisable not to stringify unnecessarily as it can be considered unnecessary)

Answer №4

options:p.optionsEN.map(item => { text: item.textEN })

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

Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Navigate the page by scrolling the absolute positioned div

Is it possible to make the fancybox modal scroll with the page using fancybox 2? I want it to move along with the content rather than being fixed in the center with a max-height restriction. How can I achieve this? $('.fancybox-open').fancybox({ ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

What is the best location for me to update the state in order to ensure that I receive the accurate information from

Currently working on a major project to showcase my development skills in an upcoming job interview, I find myself a) lacking experience and b) short on time to make any significant code changes (like implementing Hooks). The task at hand involves retriev ...

What is the best way to add an image using php, javascript, and browser storage?

Previously, I successfully uploaded an image using PHP and HTML. Now, I need to achieve the same with JavaScript (js) and AJAX. Additionally, I have been advised to utilize local storage for server-side storage before inserting it into the database. Below, ...

jQuery - translating and organizing names of countries

I have implemented a jQuery function to organize a list of country names based on the user's selected language code (via a language select dropdown). You can find more information on this topic in this related post. The translation of country names s ...

Learn the technique of coding HTML within inline JavaScript, along with implementing CSS inline styling

I'm looking for a way to incorporate HTML within inline JavaScript, along with CSS inline styles. Can someone provide guidance on how to achieve this? For example, something like the following code snippet: <p><span style="color: #00ff00;"&g ...

Retrieve the URL redirected by JavaScript without altering the current page using Selenium

Is there a way to extract the URL I am supposed to be redirected to upon clicking a button on a website, without actually being redirected? The button triggers a complex Javascript function and is not a simple hyperlink. click() method doesn't meet my ...

AngularJS is causing the D3.js Bubble chart graph to not display properly

I've been attempting to enhance my Bubble chart graph created with D3.js by incorporating AngularJS, but I'm facing some difficulties. Despite going through this tutorial, nothing seems to be working as expected. Below is the code I have written ...

Using Typescript with Angular 2 to Implement Google Sign-In on Websites

Currently, I am in the process of creating a website that utilizes a typical RESTful web service to manage persistence and intricate business logic. To consume this service, I am using Angular 2 with components coded in TypeScript. Instead of developing m ...

Determine whether a child node is an element or a text node using JavaScript

I am experiencing an issue with the childNodes property. Here is the scenario: <ol> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ol> //childNodes.length = 7 However, <ol><li> ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...

Can JavaScript alter the Page Source Code?

Something that has caught my attention recently is the behavior of my website's AJAX implementation. When my site receives a response, it is inserted into div elements using the .innerHTML method. For example: $("#cont-btn") .click(function() { ...

Passport.js: Navigating Users in the Right

I've been working on integrating passport.js, passport-google-oauth, and nodjes to retrieve a user's profile locally. However, I'm facing an issue with the redirect after logging in. Although the information is successfully loaded (I can acc ...

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet: export default { name: "ProSelect", data() { return { isActive: false ...

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...