How can an empty array be added to another array using the map method in JavaScript?

Here is the array data I am working with:

var  service: [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];

I am looking to add a static empty array within this data,

Is it possible to insert an empty array into another array using the map function?

My desired output is :

 var service: [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
                all:[]
            }];

Please provide any solutions or ideas you may have. Thank you.

Answer №1

Instead of a traditional loop, utilize the forEach method:

let data = [{id: '1', name: 'gana', age: '21', spare: 'rinch'}];
data.forEach(entry => entry.all = []);
console.log(data);

Answer №2

var newService = [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
 console.log(newService);
newService.forEach(item => item.all= []);
console.log(newService);

Answer №3

Utilizing Array#map to create a new array without altering the original.

This approach involves using Object.assign to construct a new object with the desired additional property.

var service = [{ id: '1', name: 'gana', age: '21', spare: 'rinch' }],
    withAll = service.map(o => Object.assign({}, o, { all: [] }));

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

Answer №4

To achieve the desired outcome using index, you can follow this example:

var service = [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
service[0].all = [];
console.log(service)

If you prefer using map() as mentioned in the question:

var service = [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
service = service.map(function(i){
  i.all=[]; return i;
});
console.log(service);

Answer №5

One simple way to achieve this is by using the underscore map function.

_.map([{
    id: '1',
    name: 'gana',
    age: '21',
    spare: 'rinch',
}], function(person) { person.all = [];
    return person; });

If you want to test this, you can go to underscore website, open the inspect tool, and paste the code to see the 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

Delving into the intricacies of reactivity within datasets

Seeking assistance with a component issue I am facing. I have a situation where I need to pass a prop and assign a variable from my data to that prop, but it needs to be done in a reactive manner. The child component only accepts Booleans so I cannot modif ...

Establish remote functionality for a JSON AJAX PHP form

Recently, I encountered an issue with my Javascript code that interprets JSON from PHP. Surprisingly, it works perfectly fine on my local server, but when I attempt to transfer the script to a different server, it fails to function. To address this, I have ...

Implementing interactive dropdown menus to trigger specific actions

I have modified some code I found in a tutorial on creating hoverable dropdowns from W3. Instead of the default behavior where clicking on a link takes you to another page, I want to pass a value to a function when a user clicks. Below is a snippet of the ...

The setState function in React.js fails to properly assign data

Recently, I've been using axios.get() to retrieve data from my database. The response is coming back correctly, but for some reason, when I attempt to update the state with this data, nothing seems to change. import React, { Component, useState, useE ...

Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views. I have one controller managing the behavior of this div, and another controller where I want to manipulate the v ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

Why is React App showing up twice on the webpage?

After successfully creating a React app based on Free Code Camp's Drum Machine project that passed all tests on Code Pen, I encountered an issue when transferring the code to Visual Studio. Surprisingly, the app now fails one test (#6) even though it ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...

When using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...

What is the reason behind the decision for Google Chart API to display a legend only for pie charts

I have encountered an issue while attempting to display a pie chart on an ASP.NET webpage using the provided URL: . Despite passing valid values in the URL parameters, only the legend of the chart is displayed and not the chart itself. Can anyone provide i ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

What is the reason behind Express exporting a function instead of an object in the initial stages?

In Node.js, when utilizing express, we start by using const express = require('express') to bring in the express module, which will then yield a function. Afterward, we proceed with const app = express() My inquiry is as follows: What exactly ...

When provided with no input, the function will output true

I'm having trouble understanding this problem! I've implemented a basic jQuery validation that checks if an input field is empty when a button is clicked. http://fiddle.jshell.net/fyxP8/3/ I'm confused as to why the input field still retu ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...