A method for modifying the key within a nested array object and then outputting the updated array object

Suppose I have an array called arr1 and an object named arr2 containing a nested array called config.

If the key in the object from arr1 matches with an id within the nested config and further within the questions array, then replace that key (in the arr1 object) with the value of the title property found next to that id.

Let's see an example. The key isWorking from arr1 is the same as the id value in arr2.config[0].questions[0], so change the isWorking key to the value found in

arr2.config[0].questions[0].custom.title
.

var arr1= [
  {"jobs": "Marketing","isWorking": yes,"country": "MY"},
  {"country": "IN","members": 4}
]

var arr2=
{
   "id":1,
   "name":"xxx",
   "config":[
      {
         "questions":[
            {
               "id":"isWorking",
               "custom":{
                  "title":"Are you working?"
               }
            },
            {
               "id":"jobs",
               "custom":{
                  "title":"Please specify job(s)"
               }
            }
         ]
      },
      {
         "questions":[
            {
               "id":"country",
               "custom":{
                  "title":"which Country?"
               }
            },
            {
               "id":"members",
               "type":"choices",
               "custom":{
                  "title":"How many members?"
               }
            }
         ]
      }
   ]
}

Expected output:

[
  {"Please specify job(s)": "Marketing","Are you working": yes,"which Country": "MY"},
  {"which Country": "IN","How many members": 4}
]

I attempted:

var result = arr1.map(e => ({
  arr2.config.find(i => {
    i.questions.find( q => {
     q.id === Object.key(e) ? Object.key(e) === q.custom.title : q.id
   }
 })
}))

Answer №1

Your code is missing return statements in the `find` callbacks, which are necessary when using code blocks with braces. Additionally, the outer object literal returned by the `map` callback should follow proper syntax, including spread syntax. Remember that the `find` method can only return an existing object, not create a new or modified one.

Assuming that the matching strings for the first object need to be found in the first `questions` array and for the second object in the second `questions` array.

I recommend renaming `arr2` as it is actually a plain object with a property that is an array (`config`).

You can achieve this task using `Object.fromEntries` and `Object.entries`. Here's an example:

const arr1 = [{"jobs": "Marketing","isWorking": "yes","country": "MY"}, {"country": "IN","members": 4}];

const obj = {"id":1,"name":"xxx","config":[{"questions":[{"id":"isWorking","custom":{"title":"Are you working?"}},{"id":"jobs","custom":{"title":"Please specify job(s)"}}]},{"questions":[{"id":"country","custom":{"title":"which Country?"}},{"id":"members","type":"choices","custom":{"title":"How many members?"}}]}]}

const result = arr1.map((e, i) => Object.fromEntries(
    Object.entries(e).map(([key, value]) =>
        [obj.config[i].questions.find(({id}) =>
            key === id
         )?.custom?.title ?? key, value]
    )
))

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

Error: The "render" method is not available for the IncomingMessage object

While working on a basic application using node.js and express, everything seems to be in order except for this error that keeps popping up: res.render("aggregatedCostList",{ ^ TypeError: Object #<IncomingMessage> has no method 'render&ap ...

Steps to transforming a standard array into a multidimensional array

I have a JSON array that is generated after submitting a form using the formSerialize function. Here is an example of how the array looks: [ {"name":"client_management-testmonitoring","value":"0"}, {"name":"client_operations-testmonitoring","v ...

Error message: Unable to access properties of null when calling 'registerPlugin' in @devexpress/dx-react-grid-material-ui

I have developed a CustomGrid component that is based on the DevExpress Grid component. So far, it has been working smoothly. Here's how the implementation looks like in App.tsx: import Paper from "@mui/material/Paper"; import { Table, TableHeaderRow ...

Angular form displayed on the screen

I'm having trouble finding a solution to this issue, as the form data is not being output. var app = angular.module('myApp', []); app.controller('mainController', ['$scope', function($scope) { $scope.update = funct ...

Revamp the layout of the lower HTML video menu

Here is my code: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> video { width: 100%; height: auto; } </style> </head> <body> <video width="400" controls> ...

Encountering issue while starting npm: expressjs server facing problem with MongoDB

Running npm start on Windows went smoothly, but I encountered an error when trying it on macOS. The error message is as follows: > node ./bin/www.js www error: SyntaxError: Unexpected token ? If you require any additional information, please do not he ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Error: The jQuery TableSorter Plugin is unable to access property '1' as it is undefined

I've been attempting to utilize the jquery table sorter plugin, but I keep encountering an error when trying to sort the table. The error message I'm receiving is: cannot read property '1' of undefined This is the HTML code I have: ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

PHP code for printing a JavaScript string containing a single quote

I'm encountering an issue with a script generated by PHP. When there is a single quote in the description, it throws a JavaScript error and considers the string terminated prematurely. print "<script type=\"text/javascript\">\n ...

What is the best way to update the background color for specific days in fullcalendar?

I have been working on my fullcalendar code and I am trying to figure out how to change the background color only for Feb 14. dayRender: function (date, cell) { var Xmas = new Date('2017-02-14'); var weekday = Xmas ...

React Router is used to render routes that do not match the specified path

I am utilizing TypeScript in React Router. I have defined two routes: / and /pages/id. class MyComponent extends React.Component { render() { return <BrowserRouter> <div> <Route exact path='/' ch ...

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...

jQuery - Issue arises when no radio button is selected

Currently, I am working with a group of radio buttons and need to implement validation that shows an error message if none of the buttons are checked. Is there a method to retrieve the combined value of all radio buttons at once, or will I have to indivi ...

Difficulty in constructing an array from several Firebase Storage URLs

I'm attempting to retrieve multiple image URLs and store them in an array using Firebase Storage. However, I am facing issues accessing specific index positions within the testArray: var testArray = [] listAll(ref).then((res) => { res.item ...

What is the syntax for accessing a nested object within the .find method?

Currently building an application in node.js. I am struggling with referencing the "email" element in the "userData" object within the Order model when using the find method. Any suggestions on how to properly refer to it? Order model: const orderSchema = ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...