Tips for dynamically changing the object based on the value type in JavaScript

How can I transform a nested object into a new object using JavaScript?

I have an object obj where if the details property is an array, I want to use the first value of the array as the value in JavaScript.

function transformObject(obj) {
  let map = {};
  obj.forEach(e => {
    let details = e.details;
    Object.values(details).forEach(value => {
      if (Array.isArray(value) && value.length > 0) {
        map[value[0]] = value[0];
      }
      else if (typeof value === 'object') {
        Object.values(value).forEach(val => { map[val] = val; });
      }
    })
  });
  return map;
}

var obj1 = [
  {
    details : {
      "info"  : ["stocks", "finance", ""],
      "sales" : ["analytics"]
    }
  }
];
var obj2 = [
  {
    details : {
      "city" : "SG"
    }
  }
];
var result1 = this.transformObject(obj1);
var result2 = this.transformObject(obj2);

Expected Output

// for obj1 (show only the first value from each array)
{
  info  : "stocks",
  sales : "analytics"
}
// for obj2
{
  city : "SG"
}

Answer №1

It seems like you may have made this more complex than necessary. Take a look at the following illustration for clarification. The process can be summarized as follows:

  1. Go through each details key
  2. If the value associated with the key is an array, create the key in the map and set its value to the first element of the array
  3. If the value associated with the key is not an array, simply copy it over to the map

With these steps, you should be able to attain your desired outcome.

function generateNewObject(obj){
  let map = {};
  obj.forEach(item => {
    let details = item.details;
    Object.keys(details).forEach(key => {
      var value = details[key];
      if (Array.isArray(value) && value.length > 0){
        map[key] = value[0];
      } else {
        map[key] = value;
      }
    });
  });
  return map;
}

var object1 = [
  {
    details: {
      "product":["electronics","technology",""],
      "service":["maintenance"]
    }
  }
];

var object2 = [
  {
    details: {
        "country":"US"
    }
  }
];

var result1 = generateNewObject(object1);
var result2 = generateNewObject(object2);

console.log(result1);
console.log(result2);

Answer №2

Check out this concise solution that utilizes destructuring assignments:

function createNewObject(obj) {
    const [{ details }] = obj;
    const entries = Object.entries(details)
        .map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value]));
    return Object.fromEntries(entries);
}

See it in action below:

'use strict';

function createNewObject(obj) {
    const [{ details }] = obj;
    const entries = Object.entries(details)
        .map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value]));
    return Object.fromEntries(entries);
}

const obj1 = [
    {
        details: {
            info: ['stocks', 'finance', ''],
            sales: ['analytics']
        }
    }
];

const obj2 = [
    {
        details: {
            city: 'SG'
        }
    }
];

console.log(createNewObject(obj1));
console.log(createNewObject(obj2));

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

Searching for records in Rails using a specific attribute within an associated array

There are two models, A and B. Model A has many instances of model B, with each B instance having an attribute called :number. What is the recommended Rails approach (without resorting to manual coding) to determine if a specific B object associated with ...

Pop-up window for uploading files

Looking for assistance with my file uploading system. I am utilizing a unique purple button from http://tympanus.net/Development/CreativeButtons/ (Scroll down to find the purple buttons). Additionally, I am using a wide, short content popup feature availa ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Generating DOM elements at specific intervals using Jquery

I am looking to dynamically create 1 div container every x seconds, and repeat this process n times. To achieve this, I have started with the following code: $(document).ready(function() { for (var i = 0; i < 5; i++) { createEle(i); } }); f ...

Updating a child component within a Modal: A step-by-step guide

I am using a global Modal component: export const ModalProvider = ({ children }: { children: React.ReactNode }) => { const [isModalOpen, setIsModalOpen] = React.useState(false); const [config, setConfig] = React.useState<ModalConfig | nu ...

Expanding the Angular UI bootstrap modal to fullscreen

Hey there, I've got a modal with a custom size: var dialog = modal.open({ template: content, size: size, controller:'someController' cont ...

What is preventing this from functioning properly? (html/javascript)

I need help checking if this code is correct, as I am not very knowledgeable about HTML. I would appreciate it if someone could explain it to me in simple terms so I can understand. Here is the code: <input type="text" id="user" value=""> <inpu ...

The inputmask is triggering an unhandled RangeError due to surpassing the maximum call stack size

I need to dynamically set a regex pattern on the idnumber field by selecting a different value from the idtype dropdown. Everything works smoothly until I choose the last option which contains a "?" character, causing the page to become unresponsive and di ...

Switch up the perspective/component without altering the URL

I have implemented a 404 error page functionality successfully using VueRouter: const router = new VueRouter({ routes: [ // ... { path: '*', component: NotFound, name: '404', ...

Safari on iOS 9 having trouble playing embedded YouTube videos

Recently, I discovered that my YouTube embedded videos are not playing on iOS devices when on my website unless you click in the top left corner of the video. Even after removing all extra YouTube parameters and using standard iFrame embed code, the issue ...

From Ruby to Javascript: Solving the Challenges of Date Calculation

Can you help me convert this Ruby snippet into JavaScript? I can't seem to get the expected output. Here is the original Ruby code: require 'date' moment = DateTime.new(2014, 9, 27, 0, 0, 0, DateTime.now.offset) intervals = [['day&apo ...

Using jQuery to replace an HTML element multiple times

Seeking assistance for implementing functionality that replaces a button with an input field, where users can enter information and hit enter. Once the action is completed, the original button should reappear. The current script works effectively but lacks ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following th ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

Changing an element in an array by using a specific input

With the usage of either JavaScript or Jquery, I possess an array that has been arranged in accordance with Start Date (coordinates): [{ elem: '<div id="task7">', startDate: 864, endDate: 999, order: 0 }, { elem: '<div id ...

Struggling with breaking a string into an array in C

Need help with splitting a character string into an array called temp_dow. // Here is the code to parse the incoming string char input[] = {"1111111,0000000,1010101"}; char temp_dow[3][7]; char *tok1; int i = 0; tok1 = strtok(input, ","); while (tok1 != N ...

Exploring the world of PPM image formats

: Tag P6 650, 652 255 The tag P6 signifies a PPM image format. The subsequent values represent the width and height of the image, followed by the maximum pixel value. After this header information comes binary pixel data with three bytes for color (red ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

Leveraging Vuetify on a standalone .html document

I am currently working on a personal project where I am experimenting with avoiding a full npm build process. Instead, I am trying to work within a single .html file that utilizes Vue 3 and Vuetify. Below is the complete HTML code which can be simply dropp ...