Tips for inserting a property into an array of objects when it matches the specified ID

As someone new to Angular, I am encountering an issue and would appreciate some help. Here is an array of objects I am working with:

signals = [{
'signalID': '123'
},{
'signalID': '233'
},{
'signalID': '333'
},{
'signalID': '433'
},{
'signalID': '533'
},{
'signalID': '633'
},{
'signalID': '733'
}]

Additionally, I have an object structured like this:

signalOrder = {
333:1,
433:2,
533:3
}

The goal is to add a 'orderNo' property to the signals array. If the 'signalID' matches a key in the signalOrder object, the 'orderNo' should be set accordingly, otherwise it should be null. The expected result is:

signals = [{
'signalID': '123',
'orderNo':null
},{
'signalID': '233',
'orderNo':null
},{
'signalID': '333',
'orderNo':1
},{
'signalID': '433',
'orderNo':2
},{
'signalID': '533',
'orderNo':3
},{
'signalID': '633',
'orderNo':null
},{
'signalID': '733',
'orderNo':null
}]

I believe this can be achieved using the JavaScript map function, though I am unsure of the exact implementation.

Answer №1

To achieve this, you can follow the steps below:

let signals = [{'signalID': '123'},{'signalID': '233'},{'signalID': '333'},{'signalID': '433'},{'signalID': '533'},{'signalID': '633'},{'signalID': '733'}];

let signalOrder = {333:1,433:2,533:3}

let mapped = signals.map(x=>{
  return {
    signalID:x.signalID,
    orderNo:signalOrder[x.signalID]
  }
})

console.log(mapped)

Answer №2

To achieve the desired outcome, you can utilize the Array.map() method. It involves retrieving the orderNo from the signalOrder object for each signal item and setting it to null if it is not found.

const signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': '333' },{ 'signalID': '433' },{ 'signalID': '533' },{ 'signalID': '633' },{ 'signalID': '733' }];

const signalOrder = {
  333:1,
  433:2,
  533:3
}

const result = signals.map(({signalID}) => ({ 
    signalID,
    orderNo: signalOrder[signalID] || null
}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

This particular problem does not require Angular or Typescript. Instead, it can be resolved using standard JS Array methods.

One approach involves utilizing Array#map, the spread syntax, and checking for falsy values using the OR operator ||. When accessing signalOrder[signal.signalID], the result could be undefined for non-existing properties, which is considered falsy. In such instances, the value null would be utilized.

Give this method a try:

const signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': '333' },{ 'signalID': '433' },{ 'signalID': '533' },{ 'signalID': '633' },{ 'signalID': '733' }]
const signalOrder = { 333:1, 433:2, 533:3 }

const result = signals.map(signal => ({
  ...signal,
  orderNo: signalOrder[signal.signalID] || null
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

signals = [{
'signalID': '123'
},{
'signalID': '233'
},{
'signalID': '333'
},{
'signalID': '433'
},{
'signalID': '533'
},{
'signalID': '633'
},{
'signalID': '733'
}];

signalOrder = {
333:1,
433:2,
533:3
};

signals.map(obj => {
  if(obj.signalID in signalOrder){
    obj.orderNo = signalOrder[obj.signalID]
  }
  else{
    obj.orderNo = null
  }
})

console.log(signals)

Indeed, utilizing the JavaScript map function can solve this issue. You can test the code snippet below:

  signals.map(obj => {
  if(obj.signalID in signalOrder){
    obj.orderNo = signalOrder[obj.signalID]
  }
  else{
    obj.orderNo = null
  }
})

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

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

Sending asynchronous data from parent to child components in Angular

When utilizing Angularfire2, my goal is to transmit an object retrieved from the Firebase database from parent to child components: Parent Component: @Component({ selector: 'app-page', styleUrls: ['./page.component.scss'], templ ...

Is there a way to modify the starting position of my shapes in Three.js?

Is there a way to adjust the starting position of my geometry? Currently, it appears in the center of the canvas, but I would prefer it to be at the top left corner. Any suggestions on how to achieve this? scene = new THREE.Scene(); camera = new THRE ...

What is the best way to transfer a string to a different Vue component?

Within my project, I have a masterData.js file that serves as a repository for my master data. This file retrieves data from my mongo db and distributes it to various components of the project. To facilitate this process, I have implemented a function with ...

How can I maintain query parameters in a redirected route in Angular 4?

In my app-routing.module.ts file, I have set up a route redirection like this: { path: '', redirectTo: '/home', pathMatch: 'full' } Now, let's say that in my index.html file, I have the line <base href="/mysite"> ...

Utilizing Angular's globally accessible variables

As we make the switch to Angular.js for our webapp, we are faced with the challenge of storing global data. In the past, we used a global object called app to store various functions and variables that needed to be accessed across different parts of the ap ...

Incorporating external CSS and JS files into your WordPress website

Hello, I am unfamiliar with the Wordpress framework and I am seeking guidance on how to add an external CSS and JS file to my Wordpress page. I have successfully created a new page, but would like to incorporate a CSS and JS file into it. Would creating a ...

Error in Next.js 11: Unable to access property 'canonicalBase' as it is undefined

Encountering an issue after upgrading from Next.js version 10.0.2 to 11.0.1. Since the update, I am unable to initiate a project due to the following error: Cannot read property 'canonicalBase' of undefined In my _app.tsx file, the Next imports ...

Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object. T ...

An error is thrown when using AngularJS .length property

Currently, I am carrying out a regular task within my Filter to verify if angular.module('someApp') .filter('filterSomeData',['$filter',function ($filter) { return function (items, keyObj) { var filterObj ...

Tips on using the ref attribute in Vue.js to focus on an input element

In my Vue.js component for 2FA, I have implemented the following structure: <template> <div :class="onwhite ? 'on-white' : ''"> <input :id="`n1`" ref="n1" v-model=&quo ...

What steps should I take to ensure my mineflayer sprints while trailing behind me?

I am developing a Mineflayer bot that follows me and tries to attack me. However, when I move far away from the bot, it stops following me. In addition, the bot has another issue where it falls while bridging due to its lack of intelligence. How can I im ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

Updating the image source through ajax by retrieving the location from the database

Is there a way to dynamically change the image source using AJAX? I have the location saved in my database and I want to set the img src from the value of something like data[0]['patient_photo']. Below is the HTML code for the image: <img id= ...

What is the proper way to send a list as a parameter in a restangular post request

Check out this code snippet I found: assignUserToProject(pid: number, selectedUsers: any, uid: number) { let instance = this; return instance.Restangular.all("configure/assign").one(pid.toString()).one(uid.toString()).post(selectedUsers); } ...

Inaccessible " following the "Return" Conflict

I'm struggling to resolve these warnings: Merge this with the previous "var" statement, found on lines 7, 9 and 10. Unreachable " after 'Return' - it's related to ($window.width() <= 770) { return; Script snippet: //StickyB ...