Retrieve a property from an object in Javascript without the need to declare it separately

I am dealing with an array of objects that requires looping through to create a new object with different properties. The issue arises when attempting to access a property before it is actually declared.

Here is the original object:

let data = [
  {
    "name": "one",
    "total": 12,
    "fec": "001"
  },
  {
    "name": "one",
    "total": 1,
    "fec": "002"
  },
  {
    "name": "two",
    "total": 5,
    "fec": "001"
  }  
]

This is the approach taken:

let result;
data.forEach((item) => {
  result = {
    name: item.name,
    result: data.find((item) => item.fec === '001') ?.total,
    dto: this.result + 5
  }
})

The dilemma at hand: finding a way to access the result property from within the dto property inside the forEach().

Answer №1

It is essential to assign the value to a variable before adding it to the result object.

Your current code doesn't produce all the desired results as it repeatedly replaces the result variable with a distinct object. To fix this, utilize the map() function to return all results as an array.

let data = [
  {
    "name": "one",
    "total": 12,
    "fec": "001"
  },
  {
    "name": "one",
    "total": 1,
    "fec": "002"
  },
  {
    "name": "two",
    "total": 5,
    "fec": "001"
  }  
];

let result = data.map((item) => {
  let r = data.find((item) => item.fec === '001')?.total;
  return {
    name: item.name,
    result: r,
    dto: r + 5
  }
});

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

Unable to execute form action due to recent updates in input values

I am looking to utilize an email service provided by formspree that requires a specific input format: <form action="https://formspree.io/f/*formendpoint* " method="POST" > <label> Your email: <input type=&qu ...

How can I rename attribute values in a dropdown menu and ensure they work properly?

I'm facing an issue with my code. How can I store the option values in a database when they have numbering like value="1" or value="2"? Can I change it to something like value="1000" and have the other select box change to value="250" when selected? ...

Tips for maintaining the backslash character while transforming a string into a regular expression

Received some regular expressions in a JSON object like this: { config: { regEx: "/^$/" } } Attempting to convert the string into a regex: const re = new RegExp(config.regEx); The issue is that RegExp escapes the / characters resulting in //^$ ...

In an attempt to evaluate the checkbox list values against those in an array list using C# and ASP.NET

We are in the process of developing a student information system that includes a checkbox list containing all the modules for the course enrolled by a selected student. These module values are stored in the database. Our goal is to automatically select/tic ...

Utilizing Pointers for Returning Arrays from Functions in C

I am currently struggling with utilizing pointers in my code to generate random numbers and store them in an array. Any guidance on how to incorporate pointers in this process would be greatly appreciated. #include <stdio.h> #include <stdlib.h& ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Transform the JSON data by converting the timestamps to dates using the "todate" function and flatten an array

Query: 1) I need to maintain the json data as it is but convert the Timestamp to a human-readable date format like "2016-12-19T09:21:35Z" { "Action": "ALLOW", "Timestamp": 1482139256.274, "Request": { "Country": "US", "URI": "/version/moot/ ...

Exploring Source Map Explorer in Next.js: A Beginner's Guide

Looking for assistance in analyzing the Next.js build using source-map-explorer. Can anyone provide guidance on the script? For React (CRA), the script I use is: "build:analyze": "npm run build && source-map-explorer 'build/sta ...

Uncertainty lingers over the location of where a JQuery javascript function is invoked in this particular code snippet

Hey there, I'm new to JavaScript and have a question about this demo website: The homepage header features a SlideShow created using a JQuery plugin called FlexSlider. The HTML section for this is as follows: <!-- Slider Section with Flexslid ...

Retrieve the nearest attribute from a radio button when using JQuery on a click event

I have a query regarding the usage of JS / JQuery to extract the data-product-name from a selected radio button, prior to any form submission. Although my attempt at code implementation seems incorrect: return jQuery({{Click Element}}).closest("form" ...

Steps for creating a monochromatic blinking background for notifications

Upon receiving a notification, I retrieve it from the database and activate the blinking effect on the notification box. However, I would like to stop the blinking once the user clicks to view the notification and maintain a single color display. For examp ...

The PHP function is not successfully receiving a value from the AJAX call to be entered into the Database

I've been struggling with a piece of code lately, trying to pass the value 1 to my database when a user clicks the "collect coins" button. The goal is to reset the column "dailyfree" every day at 12 pm so that users can click the button again on the n ...

What is the process of incorporating custom methods into custom constructors in javascript?

As a newcomer to javascript, I have been exploring various libraries and came across VueJS, which I find truly impressive. Take a look at this example : HTML : <h1 id="test">{{ test }}, I like Javascript</h1> JS : var vue = new Vue({ e ...

Is it possible to open a new tab by clicking on an anchor tag

I have a scenario with two tabs on a webpage, each with anchor tags that I can navigate to from the homepage using a header menu item anchor. The tabs are working fine with an active class and aria-expanded="true", but I'm facing an issue where the ap ...

Guide to linking an external URL with a lightbox image

I have created a gallery and an admin gallery page. In the admin gallery, there is a delete button that appears over the image. However, when I click on it, instead of showing the message "Are you sure?", it opens a lightbox. I suspect that the code for t ...

When sending a POST request, the req.body.someElement parameter is not defined

Encountering an issue with a post request, as req.body is returning undefined values. Despite researching on Google and Stack Overflow, the provided solutions have not resolved the problem. Although logging the name shows a value, trying to access req.body ...

Preventing functionality with Jquery hashtag in the URL

My Jquery code successfully shows and hides divs with a button click, but it seems to only work for the first two clicks. After that, a hashtag appears in the URL and the script stops functioning. I attempted to add `e.preventDefault()` at the beginning ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

Modifying the Data in the JSON_ARRAY Mysql 8.0

My current situation involves updating the hourly rate for user BOB to 600. I need to extract the hourly rate from the following JSON array specifically for the user BOB. @data = [{ "Subject": "Maths", "type": "paid", "tutor": "MARY", "hourly_rate": " ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...