JavaScript object merging (let's coin a term)

Is it possible to natively transform an object in JavaScript?

{
    sample:{
        name:"joe",
        age:69
    }
}

into

{ 'sample.name': 'joe', 'sample.age': 69 }

I have tried the following method, and it appears to work for now. However, I am unsure if this is the most efficient approach:

let test = {
  sample: {
    name: 'joe',
    age: 69,
  },
}

for (let [pKey, pValue] of Object.entries(test)) {
  for (let [key, value] of Object.entries(pValue)) {
    delete Object.assign(test, {
      [pKey + '.' + key]: value,
    })
    delete test[pKey]
  }
}

console.log(test);

Answer №1

Can you explain the reason behind wanting to do this?

If it's because you're aiming to access the object using a dot delimited string,

const name = { sample: { name: "joe", age: 69 } }['sample.name'];

you can refer to: Convert a JavaScript string in dot notation into an object reference.

Please note that the recommended approach explains why this might not be considered a good practice (and if direct access is problematic, then the remapping as shown could be even worse).


If after reading the explanation you still believe that you absolutely have to remap and flatten the object, you should aim to make it work for objects of any depth.

const input = {
  sample: {
    name: 'joe',
    age: 69,
    favorite: {
      food: 'pie',
      colors: ['pink', 'yellow']
    },
    birthday: (new Date(1980, 2, 18)) // excluded from result because Object.entries(Date).length === 0
  }
};

function recursivelyCombineKeys(obj) {
  const res = {};

  for (const [k, v] of Object.entries(obj)) {
    if (typeof v === 'object') {
      for (const [_k, _v] of Object.entries(recursivelyCombineKeys(v))) {
        res[`${k}.${_k}`] = _v
      }
    } else {
      res[k] = v
    }
  }

  return res
}

console.log(recursivelyCombineKeys(input));

Note: The general typeof v === 'object' check covers various built-in objects like Date and null, including arrays, so you may need to specify it further. See more at: Check if a value is an object in JavaScript

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

The success of your order hinges on jQuery being defined when using browserify

I encountered an issue while attempting to utilize a plugin located in /js/lib/stellar.jquery.js: var $ = require('jquery'); require('./lib/stellar.jquery') $(function(){ $.stellar(); }); Upon running the code, I received an err ...

Developing a function utilizing text data

Deciding to dive into Vue and Javascript, I attempted to streamline some code but ended up doing the opposite. So here's the issue: I have a data object in vue: eventOptions: { eventType: { data: [], ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Pre-rendering Vue.js for SEO with prerender-spa-plugin becomes unresponsive during the npm run build process

My current issue arises when attempting to execute the command npm run build while utilizing the pre-rendering plugin in my webpack configuration. I incorporated some advanced options in webpack such as: `captureAfterDocumentEvent: 'fetch-done' ...

JSON response and service status in a WCF REST service

A WCF REST service is returning a JSON response as follows: { "categories": [{ "category_id": "10", "name": "Grocery", "freeQnty":"0", "prdcost":"100" }, { "category_id": "20", "name": "Beverages", ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

What is the best way to implement rotation functionality for mobile devices when dragging on a 3D globe using D3.js and an HTML canvas?

I have been experimenting with the techniques demonstrated in Learning D3.js 5 mapping to create a 3D globe and incorporate zoom and rotation functionalities for map navigation. Here is the function that handles both zooming and dragging on devices equipp ...

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...

Encountering error code ORA-31013 while attempting to retrieve a JSON_VALUE from a JSON

When I perform a query on a JSON_TABLE extracting a value with a JSON_VALUE expression (instead of using a COLUMN in the table expression) like this: WITH SAMPLE_TABLE AS ( SELECT '{"a":[{"b":"foo"},{"b":"bar"}]}' AS PAYLOAD FROM DUAL ) SELECT ...

Sending Grunt Jade configurations to a specific file

I'm currently using grunt-contrib-jade and I'm trying to utilize the pkg.name and pkg.version variables to generate my css file name. Unfortunately, I haven't been able to make this work on my own and would appreciate any assistance. Below i ...

Using the jQuery $.each method with $.getJSON and struggling to access data within a nested array

I've been trying to achieve the same functionality in my jQuery code as my PHP code below, but so far I haven't been able to find any helpful information after nearly two days of searching. <script> $(document).ready(function(){ var s ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...

Instructions on adding the modified data to the list in AngularJS without relying on a database

Currently, I am working on an app development project using Ionic and AngularJS. The main feature of the app is to display a list of car brands along with their respective models in the first UI view. Once a user selects a car brand from the list, they a ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

How come my data cannot be displayed using ajax?

Here is the code snippet: var xml=new String(""); //function to send data every 5 seconds window.setInterval(function() { //code to obtain xml file alert(xml);// when I try alert my variable xml contain data ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...

Leveraging ray for efficient JSON file validation

I am faced with the task of analyzing a large number of JSON files to determine if they can load successfully, and then to check for specific keys within each file. Initially, I looked into using ray to speed up this process, but encountered issues when at ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...