Using Javascript to assign a new key to an object by merging existing keys

I'm struggling to articulately explain my situation, so please excuse me if this has been addressed before.

I am seeking to specify an object in the following manner:

var foo = [
   {
      firstName : 'John',
      lastName : 'Doe',
      fullName : this.firstName + this.lastName
   },
    // OR
   {
      firstName : 'Jane',
      lastName : 'Doe',
      herID : Do-something with the first and last name that were just defined, such as computeCombination(firstName, lastName)
   }
]

Can this type of declaration be achieved?

I must finalize the declaration of foo immediately and I cannot make alterations to the object later on. Additionally, I wish to avoid using indexes here, like accessing elements via foo[0].firstName etc..

The primary reason for my request is that I want to eliminate repetitive strings, since they are verbose. Furthermore, each object in the array may require a different logic for the final key.

Thank you

Answer №2

It's not possible to achieve what you're asking for using a "static" declaration as shown in your code snippet. In a static declaration, the reference to this is not set to the object, making it impossible to access other properties of the object. However, if you want similar logic for creating the fullName property, you can use a dynamic declaration with a constructor like this:

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.fullName = firstName + " " + this.lastName;
}

var people = [new Person("John", "Doe"), new Person("Jane", "Doe")];

If you need different logic for each entry, you can pass a callback function into the Person() constructor to define the specific logic to use:

function Person(firstName, lastName, fn) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.fullName = fn(firstName, lastName);
}

function combine(f, l) { return f + " " + l;}
function makeID(f, l) {return f.slice(0, 1) + l;}

var people = [new Person("John", "Doe", combine), new Person("Jane", "Doe", makeID)];

If you require different properties for each object in the array, consider using distinct constructors based on your needs. Here's an example with separate constructors:

function PersonName(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.fullName = firstName + " " + lastName;
}

function PersonID(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.herID = firstName.slice(0, 1) + lastName;
}

var people = [new PersonName("John", "Doe"), new PersonID("Jane", "Doe")];

There are various options available depending on your requirements.

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

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

Verifying Initialization Before Destructing jQuery File Upload

I'm currently working with the blueimps jQuery file upload plugin and I need to delete all existing instances before creating new ones. The issue I'm running into is that I receive an error when attempting something like this: $('.upload&ap ...

Separate arrays containing latitude and longitude coordinates to map out all potential points of (latitude, longitude)

I need to identify all potential points created by latitude and longitude coordinates stored in separate arrays: a = np.array([71,75]) b = np.array([43,42]) Is there a simple method to achieve this without generating redundant pairs? I've experimen ...

Embracing ES6 Imports Over Requires in Node.js

var MCrypt = import('mcrypt').MCrypt; What is the experience of utilizing import instead of require for the above code? It seems challenging to achieve in a single line. ...

Utilizing Time Series Bucketing in MapReduce with MongoDB

Currently, I am utilizing a schema that is centered around a time series bucketing model. My current aim involves converting certain aggregation pipelines into MapReduce models, however, I find myself stumped when it comes to identifying the equivalent of ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

One possible solution to the error of being unable to set headers after they have already been sent to the client is to ensure that the response is returned

Currently, I am working with expressJS and the following is a snippet of my code in the controller: Within the file readstream, there is a condition check that needs to be met for proper data format. If this condition is not satisfied, I do not want to co ...

Maximizing the efficiency of threejs through combining and selecting items

In my exploration of three.js optimization, I discovered that reducing the number of draw calls is crucial for improving performance. One way to achieve this is by consolidating geometries through the use of GeometryUtils.merge. Although this optimization ...

How are resolve and reject utilized within JavaScript Promises?

Initially, I believed that resolve simply passes the parameter to the function in then, so I conducted this experiment: const promise = new Promise((resolve, reject) => { resolve(new Promise(resolve => resolve(2333))) }) // promise.then(innerPromi ...

Omitted Script within a Node.js JavaScript Code Segment

My code snippet is: function write_to_orchestrate(data_to_write) { console.log('more testing'); db.put('musician', '1', '{"test":"test1"}') .then(function (result) { res.send(result); ...

Create a string representing the path to access a property within a nested object

I am dealing with an object that has nested properties: { x: { y: { z: { min: 1, max: 2 }, w: 5 } } } The levels of nesting can vary. It can end with an object containing properties like 'min' ...

How can you determine if an asynchronous function is actively running at the beginning of the "code"?

I am currently working on a project that requires access to a global context which can identify the function running at any given moment. While this task is straightforward with single-threaded synchronous functions that run from start to finish, async fun ...

Sequential Arrangement of JavaScript Functions

Does anyone know how to create an HTML element and then drag it across the screen? I have a function that defines the movement of the element, and I can click on the header to drag the div wherever I want. Additionally, I created a button to add a new div ...

Issues with C function declarations

I'm currently tackling a C assignment for my schoolwork, and the task requires us to utilize a particular function signature that is causing compilation errors on my end. Specifically, I'm encountering an error at line 38 (the smallest function ...

What exactly does the context parameter represent in the createEmbeddedView() method in Angular?

I am curious about the role of the context parameter in the createEmbeddedView() method within Angular. The official Angular documentation does not provide clear information on this aspect. For instance, I came across a piece of code where the developer i ...

Tips on stopping the display of the search input name

I am a beginner and still getting the hang of things. The code below is functioning correctly, but I'm unsure how to hide the search input name from appearing on the page. Please see the image attached below as well. Thank you for your assistance in a ...

Generating new arrays in PHP utilizing the elements of an existing array

Looking to iterate through a PHP multi-dimensional array, specifically focusing on the License array and grouping values that share the same first word into their own arrays (with the key being that word). The desired outcome is to have something similar ...

Issue encountered with ngrok causing an unidentified error in node.js while executing a server script

Recently, I've been encountering an error while trying to execute a server script in node.js. The error message I keep receiving is quite perplexing. https://i.sstatic.net/DMMSj.png Upon further investigation, I discovered that the problematic piece ...

Can spreading be used for destructuring?

These were the initial props I attempted to pass to a component: const allprops = { mainprops:{mainprops}, // object pageid:{pageId}, // variable setpageid:{setPageId}, // state function makerefresh:{makeRefresh} // state function } <Na ...

Discover every possible path combination

Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example: // Given input array with single elements or 1D arrays: let input = [1, 2, [3, 4], [5, 6]]; The unfolding process splits pa ...