Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework.

One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number']

The other array is an associated array B structured as follows:

0:[
  {
    'Stock_Number': 'GTH738', 
    'Model': 'sample_model', 
    'Type': 'sample_type', 
    'Bill_Number': 7784754,
    'some_prop1': 'prop1_val',
    'some_prop2': 'prop2_val'
  }
];

It is important to note that both arrays are dynamic in nature. Array B contains more columns than Array A, with the keys of B being a subset of A. My goal is to create a new array C consisting only of elements present in A. To accomplish this, I need to check if the key exists in B. Below is the code snippet I am using:

for(var i=0,j=0; i<B.length,j<A.length; i++,j++){
        if (!B.hasOwnProperty(A)) {
           var value = A[j];
                console.log('if-'+value); //printing value 
                console.log(B[0].value); // printing undefined 
               // C.push(B[0].value);
        }else{
            //some code
        }
    }

The resulting array should resemble the structure below:

{
'Stock_Number': 'GTH738', 
'Model': 'sample_model', 
'Type': 'sample_type', 
'Bill_Number': 7784754
}

I would appreciate any suggestions or guidance on how to achieve this task effectively.

Answer №1

Utilizing this method can be beneficial. I have enhanced the properties of object B array by adding extra attributes that are not present in array A. Consequently, these additional attributes have been removed from the objects in array C.

var A = ['Stock_Number', 'Model', 'Type', 'Bill_Number'];
var B = [
  {
    'Stock_Number': 'GTH738', 
    'Model': 'sample_model', 
    'Type': 'sample_type', 
    'Bill_Number': 7784754
  },
  {
    'Stock_Number': 'GTH740', 
    'Model': 'sample_model2', 
    'Type': 'sample_type2', 
    'Bill_Number': 7784754,
    'someProp1': 1,
    'someProp2': 2,
  }
];

var C = [];
for(var i=0; i<B.length; i++){
  var obj = B[i];
  var objKeys = Object.keys(obj);
  var resObj = {};
  A.forEach(function(itemA){
    if(objKeys.indexOf(itemA) !== -1){
      resObj[itemA] = obj[itemA];
    }
  });
  C.push(resObj);
}

console.log(C);

Answer №2

Simply swap out the line

console.log(B[0].value); 

for

console.log(B[0][value]);

Answer №3

You may choose to sort out the unfamiliar keys and construct a new object using the remaining keys.

var arrayA = ['Stock_Number', 'Model', 'Type', 'Bill_Number'],
    arrayB = [{ Stock_Number: 'GTH738', Model: 'sample_model', Type: 'sample_type', Bill_Number: 7784754 }, { Stock_Number: 'GTH738', Model: 'sample_model', Type: 'sample_type', Bill_Number: 7784754, foo: 'bar', baz: 42 }],
    result = [];

arrayB.forEach(function (b) {
    keys = Object.keys(b).filter(k => !arrayA.includes(k));
    if (keys.length) {
        result.push(Object.assign(...keys.map(k => ({ [k]: b[k] }))));
    }
});

console.log(result);

Answer №4

const stockAttributes = ['Stock_Number', 'Model', 'Type', 'Bill_Number'];
const stockDetails = [
  {
    'Stock_Number': 'GTH738', 
    'Model': 'sample_model', 
    'Type': 'sample_type', 
    'Bill_Number': 7784754
  },
  {
    'Stock_Number': 'GTH740', 
    'Model': 'sample_model2', 
    'Type': 'sample_type2', 
    'Bill_Number': 7784754,
    'someProp1': 1,
    'someProp2': 2,
  }
];

const mappedStockDetails = stockDetails.map(item =>{
    let obj = {};
    stockAttributes.forEach(key => {
        obj[key] = item[key];
    });
    return obj;
});

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

Utilizing ExpressJS in a NodeJS application with ES6 and Typescript

After confirming my information, I discovered that in an ES6 application, it is necessary to import dependencies using import .. from '..' instead of var .. = require('..'). I made the necessary changes to the imports, but encountered ...

MongoSearch: A Geo-Targeted Search Engine tailored to your needs

For my new app project, I am using MongoDB, Express, JS, and Node to create a platform similar to Yelp. After some research, I discovered how to search for multiple fields within a campus schema (including campuses, restaurants, barbershops, and names). No ...

Is it possible to create a tuple with additional properties without needing to cast it to any type?

To accommodate both array and object destructuring, I have defined the following `Result` type: type Errors = Record<string, string | null>; type Result = [Errors, boolean] & { errors: Errors; success: boolean }; I attempted to create a result of t ...

Is it possible to deactivate the error message related to "Unable to ascertain the module for component..."?

I recently incorporated a new component into my TypeScript2+Angular2+Ionic2 project. Right now, I have chosen not to reference it anywhere in the project until it is fully developed. However, there seems to be an error thrown by Angular/ngc stating "Cannot ...

The unique text: "User-defined input element disregards changes initiated through

I created a custom input component that functions correctly, but I have encountered an issue. When I attempt to update the value through a method, the model gets updated but the input value remains unchanged. Here is my component: https://codepen.io/ken-r ...

Struggling with Angular 5 Facebook authentication and attempting to successfully navigate to the main landing page

I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redi ...

The option list in AngularJS is cleared when an option is selected

In my current project, I am developing a django-tastypie api application with angularjs as the JavaScript framework. The main part of this application involves managing curriculum objects, each containing a list of grade objects and each grade object furth ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

What is the process for connecting controls to Canvas sprites?

Any input is EXTREMELY helpful! To put it shortly, I'm in need of assistance with utilizing HTML5/CSS3 buttons to manage sprite animations on my canvas. These buttons are responsible for controlling the direction and speed of the sprites independentl ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...

Utilizing PHP and JavaScript in a multi-page setting

Apologies for the length of this post in advance. I've been struggling with a coding issue for quite some time now and haven't been able to find a solution. To provide more context and help to those who might assist me, I'm including most of ...

Switching the checkbox value upon clicking a div element

One challenge I am facing is with a checkbox that saves its value and title in the local storage when clicked. This checkbox is located within a div, and I want the checkbox value to change whenever any part of the div is clicked. Despite my efforts, I hav ...

What are the best methods for improving the rendering performance of multiple sphereGeometry objects in three.js?

Looking to improve the rendering performance of sphereGeometry in my three.js program, as it is currently a bottleneck. Here is the JavaScript code I am using: var sphereThree = []; for(var idSphere = 0; idSphere < numSphere; idSphere++){ var spher ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

The function _path2.default.basename does not work when using convertapi within an Angular framework

I'm currently working on integrating the convertapi into my Angular 11 application by referencing the following documentation https://www.npmjs.com/package/convertapi My goal is to convert PDFs into images, However, I encountered an issue when tryi ...

Guide to storing a variable value when a user clicks on the client-side in a Grid View:

How can I store data in a variable on client click within a grid view? I have a Stored Procedure that returns Service Id based on the Department code provided. We are binding these details to a Grid View. How can we bind the Service Id to a variable that ...

Step-by-step guide on incorporating CSS box-shadow with the .style JavaScript property

I have a JavaScript code snippet that looks like this: document.getElementById("imgA").style.box-shadow = "0 0 5px #999999"; The hyphen in box-shadow is causing an invalid assignment exception to be thrown by the JavaScript engine (specifically in Firefo ...

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...

Is there a way to switch tabs through programming?

Is there a way to switch between tabs using jQuery or JavaScript when using the tabbed content from ? I have tried using $("tab1").click(); I have created a fiddle for this specific issue which can be found at: https://jsfiddle.net/6e3y9663/1/ ...

Retrieve an item from a table in VUE upon clicking

I am currently using Vue Bootstrap and I want to be able to access the item when a row in the table is clicked. I have set up a table and a clickmeRow method to handle the action on the clicked item. <b-table-lite hover :items="it ...