Tips for condensing my object array into a single level in JavaScript?

Hello there, I am looking to connect a dropdown menu with values from an object array. Here is what I have tried so far and need guidance on how to proceed:

JavaScript Code:

const objArray = [
    {
        "type": "select",
        "required": false,
        "label": "WorkTime",
        "name": "select-1659012135405-0",
        "customFieldId": "4330",
        "fieldCode": "WT1",
        "advancedSettings": "Edit",
        "typeDescription": "Select",
        "values": [
            {
                "label": "Apples",
                "value": "AP",
                "selected": false
            },
            {
                "label": "Bananas",
                "value": "BA",
                "selected": false
            },
            {
                "label": "Pineapples",
                "value": "PI",
                "selected": false
            }
        ]
    },
    {
        "type": "select",
        "required": false,
        "label": "WorkHours",
        "name": "select-1659012135415-0",
        "customFieldId": "13916",
        "fieldCode": "WH",
        "advancedSettings": "Edit",
        "typeDescription": "Select",
        "values": [
            {
                "label": "Day",
                "value": "D",
                "selected": false
            },
            {
                "label": "Night",
                "value": "N",
                "selected": false
            }
        ]
    }
];

const result = objArray.map(({customFieldId, fieldCode, label, values}) => {
  if (!values) { return; }
  
  return values.reduce((obj, key, index) => {
     return Object.assign(obj, {
      [`${customFieldId}-${index}`]: 
      { 
        value: `${customFieldId}-${fieldCode}-${key.value}`,
        text: `${fieldCode} - ${label} - ${key.label}`
      }
     });  
  }, {});
});

console.log(result);

Current Result:

[{
  4330-0: {
    text: "WT1 - WorkTime - Apples",
    value: "4330-WT1-AP"
  },
  4330-1: {
    text: "WT1 - WorkTime - Bananas",
    value: "4330-WT1-BA"
  },
  4330-2: {
    text: "WT1 - WorkTime - Pineapples",
    value: "4330-WT1-PI"
  }
}, {
  13916-0: {
    text: "WH - WorkHours - Day",
    value: "13916-WH-D"
  },
  13916-1: {
    text: "WH - WorkHours - Night",
    value: "13916-WH-N"
  }
}]

Expected Result:

[
  {
    text: "WT1 - WorkTime - Apples",
    value: "4330-WT1-AP"
  },
  {
    text: "WT1 - WorkTime - Bananas",
    value: "4330-WT1-BA"
  },
  {
    text: "WT1 - WorkTime - Pineapples",
    value: "4330-WT1-PI"
  },
  {
    text: "WH - WorkHours - Day",
    value: "13916-WH-D"
  },
  {
    text: "WH - WorkHours - Night",
    value: "13916-WH-N"
  }
]

I want to set up the dropdown to display "text" as the DisplayText and "value" as the Key. How can I achieve this?

Answer №1

One approach is to utilize the `flatMap` method on the outer array and then map the new object containing the inner arrays.

const
    data = [{ type: "select", required: false, label: "WorkTime", name: "select-1659012135405-0", customFieldId: "4330", fieldCode: "WT1", advancedSettings: "Edit", typeDescription: "Select", values: [{ label: "Apples", value: "AP", selected: false }, { label: "Bananas", value: "BA", selected: false }, { label: "Pineapples", value: "PI", selected: false }] }, { type: "select", required: false, label: "WorkHours", name: "select-1659012135415-0", customFieldId: "13916", fieldCode: "WH", advancedSettings: "Edit", typeDescription: "Select", values: [{ label: "Day", value: "D", selected: false }, { label: "Night", value: "N", selected: false }] }],
    result = data.flatMap(({ fieldCode, label, customFieldId, values }) =>
        values.map(o => ({
            text: [fieldCode, label, o.label].join(' - '),
            value: [customFieldId, fieldCode, o.value].join('-')
        }))
    );

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

Answer №2

If you want to enhance your approach, consider the following steps.

const updatedData = objArray.map(
  ({ specificId, codeField, description, entries }) => {
    if (!entries) {
      return;
    }
    return entries.map((item) => {
      return {
        result: `${specificId}-${codeField}-${item.result}`,
        info: `${codeField} - ${description} - ${item.description}`
      };
    });
  }
);

const refinedData = [].concat(...updatedData);

console.log(refinedData);

Answer №3

let newResult = objArray.reduce((accumulator, current) => {
  current.values.forEach(valueObject => {
    accumulator.push({
      description: `${current.fieldCode} - ${current.label} - ${valueObject.label}`,
      data: `${current.customFieldId}-${current.fieldCode}-${valueObject.value}`
    })
  })

  return accumulator;
}, []);

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

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

Working with JSON parsing in Gson or Jackson when a field can have two distinct types

My JSON data includes a field that contains two different types. "fields":[{"value":"ZIELONE OKO"},{"value":{"@nil":"true"}}] I am struggling with deserializing these values. The model class I am using has the following structure: private String value; ...

Detecting Null Values

Recently, I encountered an issue with a Javascript function I created. Despite my efforts, I was not getting the desired result. The purpose of the function is to check various variables for null values and replace them with blank spaces when necessary. He ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

Create a unique C# class specifically designed to model the structure of the JSON data

Trying to convert a JSON string into a C# class and then parse a List with a similar structure. The JSON string contains "0" and "1" values. I have used annotations to map the class properties with [JsonProperty("0")] but it seems like it's not fu ...

Tips for stopping a CSS animation from restarting when the order of a v-for rendered list is updated in Vue.js

I am working on a project that involves creating a list of data and using a template to draw blocks with time bars for each item in the list. The order of the items in the list can be updated at any time. However, I have noticed that whenever the list ord ...

Tips for creating different CSS print layouts within a single-page application

I am working on a single page application with multiple sections that need to display a list of images on separate pages. I was considering using iframes for this task, but I'm looking for advice from someone who has experience with similar situations ...

The shop is unable to find a proper reducer while utilizing redux-toolkit

I'm experiencing an issue with the configureStore function in redux-toolkit. Whenever I attempt to call dispatch on a page, I'm getting the error 'Store does not have a valid reducer'. I've double-checked my imports and ensured tha ...

Reading the Ionic2 map object is a simple task within the Ionic2 framework. Let's delve

I am attempting to retrieve an object in ionic2 that contains key-value pairs, and I need to extract the key and the brand name from it using ionic2. My question is: How can I extract the key from the object below? { "status": "success", "produc ...

Tips for effectively scaling controllers in AngularJS

I have an Angular application that is currently structured with everything in one controller. I would like to split it into multiple controllers so that each controller can focus on specific actions rather than having a mixture of functions with different ...

Save the selected data from a MySQL database into a variable using Node.js

I'm dealing with this situation: var sql = "SELECT user FROM users WHERE user = '" + req.body.user + "'"; If I have a record in the database with the user being 'babushka' and req.body.user is also 'babushka', executi ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

Utilize Javascript or Jquery to intercept and handle both GET and POST requests

Is there a method to effectively intercept and capture both GET and POST requests as they are sent from the browser to the server? In my web application, full page refreshes occur after each request is submitted, however, some pages experience delays in r ...

Preventing the submission of form post values by using jQuery remote validation

     Within my form, I have incorporated two submit buttons (save & exit, next) and implemented remote email address duplication checks. Everything is functioning properly, however, upon submission of the form, I am unable to determine which specific s ...

Error when utilizing the useLocation Hook: "The useLocation() function is only allowed within the scope of a <Router> component" in a React App

Developing a React application has led me to encounter an error while utilizing the useLocation hook from the react-router-dom library. The specific error message reads as follows: Error: useLocation() may be used only in the context of a component. In ...

In search of a Json-path or any API that can be used to update a specific value within a provided JSON string using Java

Simply put, I am on the hunt for an API that can effortlessly modify the value by taking a JSON string as the first parameter, a JSONPath as the second parameter, and the new value as the third parameter. Unfortunately, my search has only led me to this li ...

Ways to conceal a division by selecting an anchor button on this element

One thing I'm curious about is how to hide only the current div that I click on. Any suggestions on how to achieve that? $('.ads-close-btn').click(function() { $('.full-width-add').hide("slow"); }); alert('My main qu ...

Is it possible to activate the nearby dropdown based on the user's selection?

On my html webpage, I have a form that consists of three dropdown menus each with different options: The first dropdown (A) includes choices from 1 to 6, as well as 'not set'. The second dropdown (B) allows selections from 1 to 7, and also has ...

Choosing various choices using AngularJS

My goal seems simple using vanilla JS, but with AngularJS, I'm looking for the best way to achieve it within the framework. I aim to update the selected options in a multiple select box without adding or removing any options. Below is a snippet of my ...

In Swift, working with NSDictionary and NSArray are essential for handling

let voicemailFiles = voicemail.value(forKey: "voicemail") as! [AnyObject] // Encountered an issue while trying to cast type '__NSDictionaryI' (0x10ca8a228) to 'NSArray' (0x10ca89d78) let voicemailFiles = voicemail.value(fo ...