I desire to exclude the final attribute of the object and instead assign its value to the preceding property

I am dealing with an object structure like the one below:

let a = {
title: {
   value:"developer"
}
publishedOn:{
    month:{
     value:"jan"
}

    year:{
     value:"2000"
}


}

and I need to transform it into the following object format:

       let b = {
        title : "Developer"
        publishedOn:{
            month:"jan",
        
            year:"2000"
        }
}
      

The challenge is that we do not have prior knowledge of the properties inside the a variable. I attempted an iterative method, but I believe there might be a better solution out there. Any help or suggestions for improvement would be greatly appreciated.

function set(path, value) {
        var schema = obj;
        var pList = path.split('.');
        var len = pList.length;
        for(var i = 0; i < len-1; i++) {
            var elem = pList[i];
            if( !payload[elem] ) payload[elem] = {}
            payload = payload[elem];
        }
        payload[pList[len-1]] = value;
        console.log(payload);
    }


    Object.keys(this.formObject).forEach((key)=> {
        if (Object.prototype.hasOwnProperty.call(this.formObject, key)) {
            this.getPath(this.formObject[key],key).then((data:any)=>{
                set(data.path, data.value);
            });
        }
    });
}



async getPath(obj,path) { //publishedOn , month, yeaer
    let value = "";
    Object.keys(obj).forEach((key)=> {//month
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            if(key === "value"){
                path =  path;
                value = obj[key]
            }else{
                path =  path + "." + key; // publishedOn.month
                value = obj[key]['value']; // june
            }
        }
    });
    return {path,value }
}

Answer №1

One method to consider is anticipating the arrival of an object and extracting its final value.

function extractFinalValue(object) {
    return Object.fromEntries(Object.entries(object).map(([key, value]) => [
        key,
        Object.values(value).every(item => item && typeof item === 'object')
            ? extractFinalValue(value)
            : Object.values(value)[0]
    ]));
}

let input = { title: { value: "developer" }, publishedOn: { month: { value: "jan" }, year: { value: "2000" } } };
    result = extractFinalValue(input);

console.log(result);

Intended for use in older web browsers.

function extractFinalValue(object) {
    return Object.keys(object).reduce(function (r, key) {
        r[key] = Object.keys(object[key]).every(function (k) { return object[key][k] && typeof object[key][k] === 'object'; })
            ? extractFinalValue(object[key])
            : object[key][Object.keys(object[key])[0]];
        return r;
    }, {});
}

let input = { title: { value: "developer" }, publishedOn: { month: { value: "jan" }, year: { value: "2000" } } };
    result = extractFinalValue(input);

console.log(result);

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

Include the input key in the JSON response output within a Spring Boot application

Recently, I sent a post API payload with the 'key' as one of the parameters. Here is how it looked: { "key":1, "employeeId":1 } After successfully fetching the employee result through the repository, I faced an issue - How can I add this &ap ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

Having trouble loading a static image using the [email protected] component via webpack

I am struggling to display a static image in my component called Top.js. To import the image, I have used the following code in Top.js: import logo from './images/logo.png' The path for logo.png is frontend/src/images/logo.png. Next, I tried ...

The incorrect type is being assigned to an array of enum values in Typescript

Here's some code that I've been working on: enum AnimalId { Dog = 2, Cat = 3 } const animalIds: AnimalId[] = [AnimalId.Dog, 4]; I'm curious as to why TypeScript isn't flagging the assignment of 4 to type AnimalId[]. Shouldn't ...

What is the best method for accessing a store in Next.js with Redux Toolkit?

Currently, I am working on incorporating integration testing for my application using Jest. To achieve this, I need to render components in order to interact with various queries. However, in order to render a component, it must be wrapped in a Provider to ...

A step-by-step guide on importing data from an external nested JSON file and displaying its contents

CODE Having trouble displaying the results from a JSON object on my view page. The screen appears empty, but I can see the data in the console. When using ng repeat, it shows an error "Duplicate Key in Repeater." The main requirement is to print the titl ...

Can someone guide me on integrating Apache Superset as an application within a Django project?

What is the best way to integrate Apache Superset into my Django project as an app? I attempted to install Apache Superset using Docker, but now I am looking to fully incorporate the Superset tool into my Django project as one of the applications. ...

Refresh the jQuery Carousel when the window is resized to switch the orientation from vertical to horizontal

I am in the process of creating a gallery for a responsive layout, utilizing jQuery Riding Carousels for the thumbnails. You can find more information about it here. One issue I am encountering is that when the window size shrinks to be smaller than 1024p ...

Is it possible to eliminate duplicate data once it has been retrieved in a modal and used for editing purposes?

Encountering an issue where, upon clicking the modal, the second set of data is being duplicated from the first set retrieved, portrayed in these images: https://i.sstatic.net/VRRs0.png Upon clicking one of the data sets to edit, the duplication as sho ...

What is the best way to implement a JSON data Variable in a Flutter app without using a listview?

After researching numerous examples and similar queries, I'm still struggling to comprehend the task at hand. My aim is to extract specific data from an id within a JSON map in Flutter. The PHP response I obtain comprises 2 JSON strings (validated as ...

Is it possible to utilize a jQuery function to count JSON data based on specific keys and values?

function calculateJSONObjFrequencyByKeyValue(obj, key, value) { var frequencyCount = 0; $.each(obj, function(i, item) { if(obj[i].key == value){ frequencyCount++; } }); alert(frequencyCount); } calculateJSONObjFrequencyByKeyValu ...

Experiencing difficulty retrieving data by ID using CodeIgniter with JSON

Currently, I am retrieving the name of sub_regions based on their corresponding region_id using ajax. Upon joining the region and sub_region table, I can view the results within the Google Chrome console. This indicates that the query and other operations ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

When is the best time and place to break out Yahoo's Mojito Manhattan cocktail mix?

Yahoo! made headlines earlier this month by unveiling their new Mojito framework, set to be open sourced in 2012. I've been eager to learn more about this promising framework but haven't had any success so far. Does anyone know where I can find ...

What is the best way to hide the next/previous tabs once the jQuery dataTable has been set up using jSON data

Setting up a jQuery table using JSON data. Despite knowing that there will only be one row, the next/previous tabs are still displayed after the table. Is there a way to remove them? Here is the code for the table: table = $("#retrievedTable").dataTabl ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

What is the best way to reference a dynamic ID in JavaScript when clicking for an action on a different

Here is my HTML code snippet: <table> <tr> <td> @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name1" }) </td> <td> ...

The issue where all buttons in a list are displaying the same ID

I am facing an issue with a row of buttons, all having the same class add-btn. Whenever I click on one button, I intend to log the id of its containing span. However, currently, all buttons are logging the span id of the first add-btn in the list. $(&apos ...

React Nextjs implementation of a fixed navigation bar to stick at the top

Hello, I am experiencing some issues setting up a sticky navbar in Next.js. The current navbar doesn't seem to be functioning as expected. Is there anyone who can assist me with the code provided below? import React, { useEffect } from 'react&apo ...

Is there a way to determine the number of syllables in text as it is being typed?

Working on a React-based web app, I am trying to determine the number of syllables in a textarea as the user types. Encountering errors like "cannot find length of a null" at every turn. Right now, all I want is to utilize console.log() for troubleshooti ...