Creating a new nested object in JavaScript using the keys of the current object

What is the most efficient method for creating a new object based on the keys of the current object? Each key in the original object should correspond to a specific element in the new object - for example, activityName1 should match the first element's name in the nested activities array, and so on.

const obj = {
  activityName1: "Bingo",
  activityName2: "Bazinga",
  activityType1: "Dog",
  activityType2: "Term",
  description: "Games are fun.",
  name: "Patty"
};

Desired result:

const newObj = {
  activities: [
   {name: "Bingo", type: "Dog"},
   {name: "Bazinga", type: "Term"}
  ],
  description: "Games are fun.",
  name: "Patty"
};

I initially considered using reduce and Object.assign, but I only ended up with a single key/value pair:

Object.keys(variables).reduce((obj, key) => {
  if (key.includes('activity')) {
    return Object.assign(obj, {
     [key[key.length - 1]]: { activities: { [key]: variables[key] } } });
  }
  return obj;
}, {});

This resulted in an activities array like:

[
  1: {activities: {type: "Dog"},
  2: {activities: {type: "Term"}
]

Answer №1

One way to utilize mapping is by searching for keys that begin with activityName and using them to construct an array of activities. By substituting activityName with activityType, you can determine the associated type.

const obj = {
  activityName1: "Bingo",
  activityName2: "Bazinga",
  activityType1: "Dog",
  activityType2: "Term",
  description: "Games are fun.",
  name: "Patty"
};

var result = {
   activities: Object.keys(obj).filter(k => k.startsWith("activityName")).map(k => ({
       name: obj[k],
       type:obj[k.replace("activityName","activityType")]
   })),
   description: obj.description,
   name: obj.name
}

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

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Having trouble logging out of ADFS 3.0 using Internet Explorer

We have successfully created an MVC/Angular application integrated with ADFS. Due to the Angular framework, a wrapper had to be developed around ADFS in order to capture the token and utilize it as a claim for access within angular. The primary method res ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

I am looking to dynamically print countries from an array in my code based on the selected option

I'm in need of some simple code assistance. I want to display a list of countries that correspond to a selected letter, but I'm struggling to do so dynamically at the moment. For example, if I select the letter A from a dropdown menu, I want the ...

My code is refusing to accept basic string inputs in C with the getchar function

int count0=0,count1=0,cnt=0; char str[200]; char ch; ch= getchar(); while(ch!='\0') { str[cnt]=ch; cnt++; } str[cnt]='\0'; printf("%s",str); expected output : shu ...

What is the best way to toggle between different sections of a webpage using HTML, CSS, and Javascript?

I am looking to display unique content based on the user's selection of different month/year options on the same page. For example, if the user chooses March 2021, I would like to show them events specific to that month. Here is a screenshot for refer ...

Displaying the countdown of days and hours until a specific date is just a matter of using

Currently, I am tackling a project that necessitates a specific text response related to a date object. "1 day 7 hours away" --- This format is crucial; alternatives such as "31 hours away" or "1 day away" will not suffice. -- For language switching purpo ...

Cease the execution of the express function once a response has been sent

Recently delving into the world of .js and .ts, I've been exploring express.js. Take a look at the snippet below: private post = async ( request: express.Request, response: express.Response, next:express.NextFunction) => { await this.myfu ...

What causes a C array to degrade into a pointer when passed with a size parameter?

I comprehend the reason why an array transforms into a pointer when passed to a function without specifying its size, for example: void test(int array[]); Why does it still decay when passed with the size? For instance: void test(int array[3]); I am fa ...

Creating a line break in a Vue.js confirmation dialog is a helpful feature that can be achieved with a

Is there a way to add a new line after the confirmation dialog question and insert a note below it? this.$dialog.confirm("Create Group","Would you like to create group "+ this.groupName +"?<br/>(NOTE: Selected project or empl ...

Obtain the in-flow position of a DOM element

alert("Incorrect (red): " + document.getElementById("target").getBoundingClientRect().top); alert("Proper (blue): " + document.getElementById("wrapper").getBoundingClientRect().top); #target { transform: translate(20px, -20px) rotateZ(20deg); backgroun ...

Adapting my JavaScript code to handle one-dimensional CSV data instead of the usual two-dimensional format

How can I effectively parse this CSV file using JavaScript? 1363085391,42.890000000000,5.432200000000 1363088879,47.570000000000,4.981800000000 1363120475,56.560000000000,1.768000000000 1363132522,53.000000000000,1.000000000000 1363214378,48.630000000000, ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

Numerous inline notations in html code

I need help figuring out how to prevent a hyperlink from opening a new tab by commenting out the HTML code. <a href="<!--http://www.google.com=-->" target="_blank" onclick="javascript:alert('Navigation Prevented')">CLICK HERE FOR GOO ...

Personalized features to enhance Angular control

I'm in the process of dynamically loading a controller based on various values and I'm looking for the most practical way to accomplish this task. Details below. I'm attempting to access the value of the data-post-id attribute within the co ...

Why isn't my NPM package functioning properly within the Laravel framework?

I recently developed an npm package for my personal use, but encountered a ReferenceError when attempting to utilize it in a Laravel project. Here's the breakdown of what I did: I followed a tutorial on initializing an npm package, and it functioned p ...

I'm having trouble with res.redirect, why isn't it redirecting me as expected?

In my login controller, I have a form that updates the user's scope when they click a button triggering the login() function. .controller('loginCtrl', ['$scope','$http',function($scope,$http) { $scope.user = { ...

Guide to using a Selector in a mixin in VUE

I'm attempting to create a Mixin that will help me calculate the offsetWidth of an element. Here is my Mixin: export const boxWidth = (selector) => ({ mounted() { selector.addEventListener( 'resize', this.setBoxWidth ); ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...