Traversing an object and assigning its properties as values in another object using JavaScript

I need to create an object using an array as keys and another object with default properties as values. I am unsure of how to loop through and assign the key/value pairs to the new object. Can you help me out? Thank you!

The object myFinalObj is initially empty.

This is my starting object:

var startingObj = {
  'one' : {'default': 1, 'name': 'un'},
  'two' : {'default': 2, 'name': 'deux'},
  'three': {'default': 3, 'name': 'trois'}
}

Here is my array:

var myArray = ['one', 'two', 'three'];

This is what my final object should look like:

var myFinalObj = {
  'one' : 1,
  'two' : 2,
  'three' : 3
}

Answer №1

const myNewObject = myArray.reduce((accumulator, name) => { 
  accumulator[name] = startingObj[name].default;
  return accumulator;
}, {})

Referencing MDN documentation:

The reduce() function executes a provided function for each value of an array (from left to right), resulting in a single output value.

Arrow functions are a relatively new feature in JavaScript. If they are not supported in your environment, you can use the longer but equivalent syntax:

 const myNewObject = myArray.reduce(function(accumulator, name) { 
  accumulator[name] = startingObj[name].default;
  return accumulator;
}, {})

For older versions of Internet Explorer (IE < 9), the reduce function may not be available. In such cases, you can utilize the polyfill provided in the same MDN article.

Answer №2

let initialObject = {
  'red': {
    'default': '#FF0000',
    'name': 'rouge'
  },
  'blue': {
    'default': '#0000FF',
    'name': 'bleu'
  },
  'green': {
    'default': '#00FF00',
    'name': 'vert'
  }
}

let colorArray = ['red', 'blue', 'green'];

let finalResult = {};

colorArray.forEach(function(color){
 finalResult[color] = initialObject[color]['default']; 
}

Answer №3

To assign values to property keys, use the syntax obj["key"]=value. The following code snippet demonstrates how this can be implemented:

var resultantObj={};
for(var j=0;j<array.length;j++){
    resultantObj[array[j]]=initialObj[array[j]];
}

Answer №4

To ensure compatibility with older browsers, it is recommended to use either for(.. in ..) or for (var i=0;i<..;i++) instead of Array.forEach.

var myArray = ['apple', 'banana', 'cherry'];
var startingObj = {
  'apple' : {'default': 1, 'name': 'red'},
  'banana' : {'default': 2, 'name': 'yellow'},
  'cherry': {'default': 3, 'name': 'red'}
}
var myFinalObj = {};
for (key in myArray) {
myFinalObj[myArray[key]] = startingObj[myArray[key]].default;
}
console.log(myFinalObj);

Answer №5

Give this a shot:

let initialObject = {
  'one' : {'default': 1, 'name': 'un'},
  'two' : {'default': 2, 'name': 'deux'},
  'three': {'default': 3, 'name': 'trois'}
}

let myArray = ['one', 'two', 'three'];

let finalObject = {}

for(let item of myArray){
    if(initialObject.hasOwnProperty(item)){
        finalObject[item] = initialObject[item].default
    }
}

Answer №6

function constructObject(initialObject, keysArray, resultObject) {
  var currentKey;
  for (var index = 0; index < keysArray.length; index++) {
    currentKey = keysArray[index];
    resultObject[currentKey] = initialObject[currentKey]['default'];
  }
}

var finalObject = {};
constructObject(initialObj, keyList, finalObject);

Answer №7

Try out this straightforward code snippet:

const finalObject = {};
initialArray.forEach((parameter) => {
    finalObject[parameter] = baseObj[parameter].default;
});
console.log(finalObject);

Answer №8

Does this code snippet reflect your desired outcome? From the provided test case, it appears to be functioning as expected.


var initialData = {
  'one' : {'default': 1, 'name': 'un'},
  'two' : {'default': 2, 'name': 'deux'},
  'three': {'default': 3, 'name': 'trois'}
}

var targetArray = ['one', 'two', 'three'];

var resultObject = {};

for (var index = 0; index < targetArray.length; index++){
    for (var property in initialData){
        if (property == targetArray[index]){
           var value = initialData[property]['default'];
           break;
        }

    }
    resultObject[targetArray[index]] = value;
}

console.log(resultObject);

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

Timepicker.js - Incorrect Placement of Time Picker in Certain Scenarios

Utilizing the timepicker.js library to select a time, I am encountering an issue. When clicking on the input field, the timepicker should appear next to it. This function works as expected when the input is within the main view of the document. However, if ...

What is the best way to utilize the history prop in conjunction with other props?

I am currently using react-router-dom along with react. My goal is to include additional props along with the history prop import React from 'react'; function MyComponent({ history }) { function redirect() { history.push('/path&ap ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...

Storing User IP Address in Database with Express and Mongoose

I'm looking for a way to store users' IP addresses in mongoDB by using a mongoose model file for the user. Does anyone have any suggestions on how I can achieve this? Here is an example of the schema for the Users module file: const userSchema ...

AngularJS displays true for $scope.form.$submitted

I am working on a multi-step form and I am facing an issue with controlling user submissions. I need to validate each step before proceeding to the next one. Even though I am implementing validation checks and moving to the next step accordingly, the $scop ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

Steps for obtaining images using lazy loading: <img loading="lazy"

After successfully utilizing the JavaScript-executer to locate the ImageElement, I encountered an error when attempting to extract the URL for downloading the image.svg. The error message reads "NoSuchElementException." Below is a snippet of my code: ((J ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

Determine the quantity of posts currently in the Div

Hello, I am facing an issue where I am trying to determine the number of currently displayed posts in the content area. Even though there are 3 posts currently displayed, when I check the length, it is returning 1. $(document).on("click", ".load-more", fu ...

Safeguard sub-pages with Passport Local if the user has not logged in

I attempted to follow a tutorial on local authentication with Passport and Express, but I am encountering difficulties in protecting my pages for users who are not logged in. My goal is to redirect them to the login page. I experimented with creating midd ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

Using a React PureComponent to pass parameters from a Child component

I am facing an issue with my TodosList component that displays a list of individual Todo components. Below is the code snippet for the Todo component: export class Todo extends React.PureComponent { render() { return ( <li onClick={this.pr ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

Searching through a JSON object on a Laravel web page using JavaScript or AJAX for live filtering purposes

After diving into AJAX and JavaScript, I find myself needing to replace some outdated Angular functionality on our Laravel site. The specific task at hand is creating a live search filter for a page with a static header search bar. The main requirement is ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

Unexpected behavior from Internet Explorer - Span contents remain unchanged despite valid input

I have a simple question because I'm feeling a bit lost. Check out this JSFiddle link It seems that in Internet Explorer, the contents of my span won't update even though the input is valid. However, in other browsers, the span content changes ...

What are the steps to switch multiple CSS styles for creating a dark mode?

I'm currently using a combination of HTML, CSS, and JavaScript to construct my website. One feature I'd like to implement is a Darkmode switch button that toggles between Dark and Light mode when clicked. However, the issue I'm facing is tha ...

Exploring through an array tree structure?

My menu displays the "selected" array as options. When an option is selected, its branches are rendered as new options. To keep track of the traversal, I create an array called select. For example, if someone selects the 3rd option, then the 1st option, a ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

What is the best way to retrieve data for a Dojo Dgrid Table using AJAX?

Currently, I am in the process of considering DGrid for my web application. My goal is to create a table layout similar to the one demonstrated here. For reference, the code for the example can be found here. The table in question utilizes a memory store ...