Transforming arrays with map or alternative methods in javascript

Below is the JSON object I am working with:

{
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
}

My desired output should look like this:

[
  {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:5},
  {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:1}
]

Answer №1

It's a wise choice to use .map in this scenario. The issue lies in attempting to update an object, as objects are passed by reference. Consequently, all the objects will share the same id. To avoid overwriting values, you need to create a copy. One way to achieve this is by utilizing Object.assign.

var data = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
};

var result = data.storeId.map(function(id){
  return Object.assign({}, data, {storeId: id});
});
console.log(result)

If you are hesitant to use ES6 features, you may find this helpful: How do I correctly clone a JavaScript object?

Answer №2

Utilizing the power of the .map() function, you can iterate over the elements in the array storeId and create a new object with each element as the value of storeId.

var obj = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
};

var data = obj.storeId.map(el => {
  let newObject = Object.assign({}, obj);
  newObject.storeId = el;
  return newObject;
})

console.log(data);

Answer №3

To generate an object containing all existing properties along with individual storeId, you can utilize the array#map method along with spread syntax.

var obj = {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId: [ 5, 1 ]}
    result = obj.storeId.map(storeId => ({...obj, storeId}) )
console.log(result);

Answer №4

let complaintData = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
}


let transformedData = complaintData.storeId.map(store => {
  return({
     id: complaintData.id,
     cno: complaintData.cno,
     username: complaintData.username,
     name: complaintData.name,
     desc: complaintData.desc,
     storeId: store
  })
});

console.log(transformedData);

After attempting this solution, I was able to retrieve the desired result. Do you think this is an effective approach?

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

Unable to fetch all data from the Json file

I have been retrieving JSON data from and then displaying the titles in a ListView. The code seems to be functioning correctly, but I am facing a challenge where some titles are getting skipped in my ListView and one particular title is being repeated. I ...

The AJAX request and UPDATE query are not working as expected

Currently, I am attempting to use an UPDATE query with an AJAX call to update a player's division by sending it to the update_divisions.php file. The process involves selecting a user from one select box and choosing the desired division from another ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Looking for an alternative method since jQuery has deprecated the use of '.toggle()' function

After jQuery deprecated the .toggle() method, I have been searching for a new and simple solution to implement a "Read more" button that slides down a paragraph while changing text to "Read less". Below is the code I have put together: var moreText = "Re ...

What is the designated action or code in question?

let specialty = ''; function isVegetarian() { }; function isLowSodium() { }; export { specialty, isVegetarian }; export { specialty, isVegetarian }; The explanation from the editor was as follows: When exporting objects, it is done by the ...

Using React Native to create a concise text component that fits perfectly within a flexbox with a

Within a row, there are two views with flex: 1 containing text. <View style={{ flexDirection: "row", padding: 5 }}> <View style={{ flex: 1 }}> <Text>Just a reallyyyyyyyy longgggg text</Text> </View> ...

Issue with normalizing UV coordinates to a range of 0 and 1 in threejs

I am facing an issue where my model has UV coordinates that are outside the range of 0 and 1. I have attempted to normalize these coordinates with a function, but the results are not as expected. This is the function I am using to convert the UV coordinate ...

Guide to extracting and transferring multiple selected values from an array to a different UITableView using a UIButton

I have a scenario where I need to transfer selected values from one UITableView to another by tapping an Add button. Currently, I have two UITableViews in a single UIViewController. Here is what I have done so far: Loaded JSON responses into tableview1 a ...

Establish a variable in XSL to define the tabIndex

My XSL code has been designed to read an XML file and generate input elements of type text for each child node. The XML file structure is as follows: For node c, two input boxes are created in the format: Label(com 1) :input box--------------------- Label ...

Prevent the running of JavaScript events initiated by a script fetched through AJAX

In my JS application, I am using AJAX to load different parts of the application. After the AJAX function is completed, the corresponding script is executed. However, I am facing an issue when trying to load a new part of the application. I need to find a ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Is npm create-react-app giving you trouble?

When attempting to create a React app using the command npm create-react-app appname, the tool would just return me to the same line to input more code. I also gave npx a try, but encountered some errors in the process. See this screenshot for reference: ...

Silent response upon click event listener

I'm having an issue with a navbar item not calling the reverseService function on click as expected. Although my IDE is indicating that the reverseService function is never used, VueJS dev tool doesn't show any problems. However, manually changi ...

Validating JSON arrays with RAML

My API RAML includes a query parameter called 'sfIds' that is of type array. I want to ensure that the elements within this array are always numeric, like [111, 222, 333] or [111]. Any non-numeric values in the array, such as [ABC,111], should no ...

What is the best way to design an HTML page so that it changes its title daily?

I have a goal to change the site's title every day, but I am not an experienced programmer. I know that this can be done using JavaScript. I came across this idea: setInterval(function() { //change title //document.title = "Some new title"; ...

Encountering a fatal error in the Next.js application: "Mark-compacts near heap limit allocation failed issue is hindering the smooth

When I'm working in Next.js, I often encounter the issue of not being able to run my project after work. https://i.stack.imgur.com/IA5w3.png ...

How can we enable SOAJS to operate on NodeJS versions higher than 0.12?

Currently, We were required to revert our NodeJS platform back to version 0.12 in order for our SOAjs dashboard to function properly. What changes need to be made in our SOAjs implementation to support the latest NodeJS versions? Thank you ...

What is the best method for tracking the execution time of functions in Node.js?

My nodejs application has numerous functions that need to be executed. I am looking for a way to log the time taken to execute each function. For example, when my app runs these functions: execfn1(); -> should output in some log, takes: 1ms.. execfn ...

What is the most optimal jQuery code to use?

Just wondering, which of the following code snippets is more efficient (or if neither, what would be the best way to approach this)? Background - I am working on creating a small image carousel and the code in question pertains to the controls (previous, ...