Swapping out an Array of Objects with a new Array in JavaScript

I am working with an Array of Items, each of which has a set of Properties. One specific property is called config: object[], which is an array of Objects.

While I usually provide the complete object with the correct config array of objects, there are times when I need to pass different config options for certain tests. For instance, wrong config array, empty array, etc.

Below is my code snippet:

    const connectionResources = [Array.forEach(object => object.config === [])]
    connectionResources.forEach(builtInOptions => console.log(builtInOptions))

This is what I have attempted so far. I tried to spread the Array, but unfortunately, it did not work as expected.

Could someone offer some guidance on how to achieve what I am aiming for? Essentially, I want the Array of Objects to have an empty config array property instead of the original object. How can this be accomplished?

Answer №1

Attempting to spread the Array was unsuccessful for me as well.

First and foremost, if you wish to spread an array, make sure to utilize the spread operator; for example, ...myArray.

Array.forEach

Furthermore, Array.prototype.forEach yields undefined, while Array.forEach is indeed undefined (unless your array is named Array, which is not recommended as it would overshadow the Array class).

To address the issue at hand, what you actually need is Array.prototype.map

let original = [{a: 3, config: [4, 5], b: 6}, {a: 13, config: [14, 15], b: 16}];

let emptyConfig = original.map(o => ({...o, config: []}));
let hundredConfig = original.map(o => ({...o, config: [100, 101, 102]}));

console.log(original);
console.log(emptyConfig);
console.log(hundredConfig);

Answer №2

Illustrative data

const library = [{
    settings: [{}, {}]
}, {
    settings: [{}, {}]
}];

No content in the settings property

library = library.map(item => {
    item.settings = [];
    return item;
});

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

Validation of Checkboxes if Duplicable

I am currently working on form validation and have encountered an issue with multiple checkboxes. The first checkbox validates properly, but duplicates do not. Any help would be greatly appreciated. I understand that the code is not very efficient, but I ...

Are there any CSS hacks available to address the combination of position: sticky and overflow within the parent element?

I've encountered a sticky position issue when the overflow property is set to auto on a parent element. I've tried various solutions like adding an extra wrapper or using clip instead of auto, but none have worked. While I did find a solution usi ...

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...

Refreshing JSP Pages with Updated ActionBean Variables in Stripes Framework

Having recently started working with Stripes, I am trying to customize the number of records displayed on a paginated table based on the dropdown selection ("show ## records per page"). However, I am struggling to set the value of the "recordsPerPage" vari ...

invoking a SOAP endpoint with Node.js

I've recently delved into the world of Node.js and I'm attempting to integrate a SOAP service using the node soap extension. Right now, I'm just experimenting with a sample service call but I'm encountering some issues getting it to wor ...

Filter kendo grid by selecting multiple options from a drop-down menu in the mult

I am working with a kendo grid and an HTML drop down. When I set the drop down to single select, I can successfully filter the kendo grid based on the selected item's string value. Below is the filtering code that works for single select: $("#Locati ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Looking to transfer data between pages using node.js and ejs for database access?

I am aiming to showcase the logged in username and quiz points on each page after the user logs in, and to increase the user's score when quiz answers are correct. I'm considering creating a straightforward JavaScript-based quiz, and then updati ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

How can ThreeJS utilize CSS3Renderer and WebGLRenderer to display two objects in the same scene and achieve overlapping?

JSFiddle : http://jsfiddle.net/ApoG/50y32971/2/ I am working on a project where I am using CSS3Renderer to render an image as a background projected as a cube in the app. However, I also want to incorporate objects rendered using WebGLRenderer in the mid ...

When using Material UI TextField with input type "date", the event.target.value does not seem to be accessible

I am currently working with Material UI and React Grid from DevExtreme to build a table that includes an input field of type date. However, when I attempt to enter the date, it does not register the change in value until I reach the year field, at which po ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

Struggling to access a nested object within JSON using dot notation

Currently, I am utilizing mongoose and express to interact with data stored in MongoDB. I am able to view the JSON data when I reference the database. However, I encounter an issue when attempting to specifically target an object nested within the data, as ...

Async await function two is failing to execute

I am currently working on a process where I need to unzip a file first, wait for the unzipping process to complete, and then loop through each extracted file to upload it to an S3 bucket. The unzipPromise function is working as expected, successfully unz ...

Socketio: Issue: Isolated surrogate U+D83D is not a valid scalar value

I've been experiencing frequent crashes with my node.js server recently, all due to a recurring socket.io error. It seems that the client may be sending invalid UTF strings, causing an error in the utf8.js file. I'm getting frustrated with the co ...

What is the best way to loop through a JSON array in JavaScript?

Here is the JSON data I am working with: let jsonData = { "result": [ [ { "PARAM 1": [ { "field": "firstName", "message ...

Tips for properly sending an array containing objects in JSON format using Swift for iOS development

As a beginner, I am trying to grasp the concept of sending an array with objects. Does the server recognize arrays like Int, Strings, or Booleans? Do I need to convert the array into a string for JSON data? There seems to be something I'm missing. va ...

What could be causing the Angular error related to this HttpHeader?

Is there anyone who can assist me with why I am encountering an error in my Angular code while trying to use HttpHeaders to read the response status from the backend? Here is the specific error message: https://i.sstatic.net/tQu5t.jpg import { Injectable ...

The data retrieved from the backend is being stored in an object, however, it is not directly accessible through

After receiving data from the backend and storing it in an object, I am facing an issue where trying to print it using object properties shows undefined values. Here is a snapshot of my output: view image here Snippet of my code: this.documentService.getD ...

Adjust the height of an element when an animation is initiated (Angular)

Check out the transition I've set up to smoothly slide between my views: https://plnkr.co/edit/yhhdYuAl9Kpcqw5tDx55?p=preview To ensure that both 'panels' slide together, I need to position the view absolutely. However, this causes the view ...