methods for dynamically assigning values to keys while iterating over an object

Hey there,

I've encountered a problem that I need help with: I have an object containing keys and values, and I want to create a new array of objects using this data. Below is the code snippet illustrating my issue.

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = [];

for (let value of sourceObj) {
  for (let i = 1; i < 6; i++) {
    const targetObject = {
      foo: "foo",
      year: value.test + i,
      bar: "bar"
    };
    myTable.push(targetObject);
  }
}

console.log(myTable);

// expected output
// [
//   {
//     foo: "foo",
//     year: "a",
//     bar: "bar"
//   },
//   {
//     foo: "foo",
//     year: "b",
//     bar: "bar"
//   },
//   ...
//   {
//     foo: "foo",
//     year: "e",
//     bar: "bar"
//   },
// ]

Answer №1

To obtain the desired object, you can loop through the keys of an object and utilize the array.map method.

const exampleObject = {
  item1: "apple",
  item2: "banana",
  item3: "cherry",
  item4: "date",
  item5: "elderberry"
};

const myNewArray = Object.keys(exampleObject).map((key) => {
  return {
      propertyA: "valueA",
      name: exampleObject[key],
      propertyB: "valueB"
    };
});

console.log(myNewArray);

Answer №2

One way to approach this is by utilizing the Object.values method combined with mapping through the values.

const dataObj = {
  item1: "apple",
  item2: "banana",
  item3: "carrot",
  item4: "date",
  item5: "eggplant"
};

const newData = Object.values(dataObj).map(item => ({
  prop1: "prop1",
  item,
  prop2: "prop2"
}))
console.log(newData);

Answer №3

let data = {
  val1: "apple",
  val2: "banana",
  val3: "cherry",
  val4: "mango",
  val5: "orange"
};

const tableItems = [];

for(key in data){
  tableItems.push(
    {
      label : "label",
      value : data[key],
      type : "type"
    }
  );
}

console.log(tableItems);

Answer №4

Give this a shot:

const newTable = Object.values(originalObj).map((item) => ({
    name: "name",
    timestamp: item,
    description: "description"
 }));

Answer №5

To iterate through all properties of an object, you can utilize the for...in statement

When using the for...in statement, it will loop over each enumerable property in an object that is keyed by strings (excluding Symbols), which also includes inherited enumerable properties.

const sourceObj = {
  test1: "a",
  test2: "b",
  test3: "c",
  test4: "d",
  test5: "e"
};

const myTable = [];

for (let key in sourceObj) {
    const targetObject = {
      foo: "foo",
      year: sourceObj[key],
      bar: "bar"
    };
    myTable.push(targetObject);
}

console.log(myTable);

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

Node.js exec command encountering an uninformative error message and not executing properly

Here is the snippet of code that needs to be executed cp.exec("cc -Wall /tmp/test.c -o /tmp/test", function(e, stdout, stderr) { if (e) { var errorstr = "There was an error during compilation: "+ e.message.toString() ...

JMeter recording displays a script alert error notification

After recording the JMeter script on blazemeter, it initially worked fine on the website. However, upon running the jmx file, I encountered an error message: "alert("Something went wrong. Please try again");window.history.back();" I&a ...

Utilizing jQuery to check for the presence of a DIV on a page and dynamically applying CSS to another DIV

Just starting out with jQuery and feeling confident about the basics, but struggling to make it all come together. For example: If the page contains a div with the ID of #dynamicChat, then set the height of the div with the class .prdSection to 25px. Ot ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Setting up the InMemoryCache in Vue ApolloConfiguring the InMemoryCache

I've set up vue-apollo following the instructions in the apollo.config.js file from this guide: (I'm using VSCode). Now, I want to configure the InMemoryCache to exclude the typeName (addTypename: false) like it's explained here: https://w ...

Accessing this.href from the ASP.NET code behind using Javascript

I'm trying to pass this.href from my asp.net code behind to JavaScript. When I run the code, the value appears as 'undefined' in the alert message. Can anyone help me with this issue? Page.ClientScript.RegisterStartupScript(this.GetType(), ...

Guide on turning JSON into a Dictionary with Swift 3 Vapor

When making REST calls from my Vapor server to a Firebase server, I receive a JSON object as the response. I need to extract the elements under a timestamp value labeled "1508321173" from the JSON object without knowing the actual timestamp. Since this ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...

The error message encountered was: "jQuery has not been defined."

I'm struggling to understand why I'm encountering this issue. Take a look at the code snippet below: <head> <script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" type="text/javascript"></script> ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Guide on changing image source using a function

I am looking to dynamically set the img src="" attribute using a JavaScript function that changes the image based on a variable and checks its values: Here is the JavaScript code in the file: function myFunctionstatus(){ var ledactual = document.getE ...

A guide to making API calls in node.js with JSON data in the body

I am looking to send HTTP requests to an external API service. The web server I am trying to communicate with requires specific headers and a JSON payload in the request body. After researching, I found the request package which seems promising for this ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Why am I unable to utilize res of type NextResponse in my API endpoint?

I currently have a dynamic API route file specifically designed for handling POST requests. Below is the code snippet of this file: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import ...

Tips on including variables within quotation marks in JavaScript

I'm currently working on a JavaScript project using Pug. My goal is to use Express and MongoDB to develop a CRUD application that generates an edit button for each post, triggering a specific event when clicked. However, instead of the desired resul ...

Currently in development is an exciting MMORPG created with Node.js, Express, and HTML. Players will have the ability to move exclusively to

I'm developing a multiplayer online role-playing game (MMORPG) using Node.js, Express, and HTML. Currently, I'm facing an issue with keyboard interactivity in my game. When I load the game, only the 'D' key seems to work, allowing the p ...

Transferring Information Across Javascript Documents

I am facing a dilemma with using JSON data generated by one script in another script. I am unsure where to begin and have considered saving the JSON string to a text file for the second script to use, but this feels like a workaround rather than a proper s ...

Mastering the comprehension of JSON objects with jQuery by transferring data via AJAX requests

I recently encountered a challenge where I had to work with an array of values and then convert it to JSON in order to insert it into an attribute. Here's what the code snippet looked like: <div data-categories="[[{"id":"4123","name":"Sushi Restau ...

A Symfony2 controller needs to be able to return two different types of values: one for the Symfony application itself and another for a mobile application in JSON format

I am currently working on developing a restful JSON api for my Symfony2 Application. To serialize my Entities to JSON, I am utilizing the JMS\Serializer Bundle. Here is an example Controller-Action I have: public function getFarmerByNameAction(Req ...