Creating a new object by extracting various properties from an array of objects using Javascript

Trying to achieve the following:

I possess an array of objects ,


var arr = [
  { key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
  { key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];

I aim to extract the "text" and "field" from it and create a new array of objects like this:

result = [ { "field" : "firstName" , value : "aabFaa" , type :"add"}, 
           { "field" : "firstName" , value : "aAaaaa" , type: "add"}
         ]  

The "type" is predefined, while the rest are retrieved from the "arr"

What's the most efficient way to accomplish this?

Attempted this:

var arr = [
  { key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
  { key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];

let result = arr.map(a => a.text); 
console.log(result)

However, multiple lines were needed for desired properties. Is there a simpler solution?

Answer №1

Utilize the map function in combination with Object Destructuring.

var arr = [
    { key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
    { key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
  ];

const output = arr.map(({field, text}) => ({field, value: text, type: "add"}));

console.log(output);

Answer №2

When considering the use of map, it's important to note that it will create a new object with multiple properties, not just one:

let updatedValues = array.map(item => ({textValue: item.text, actionType: 'add', fieldName: item.field}));

Answer №3

const updatedData = elements.map(item => ({
    category: item.category,
    description: item.details,
    action: "update"
}));

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

Toggle the class of a selected data attribute on another div when clicked

With a click event, I attempt to dynamically add/remove classes by using data attributes on another div. Upon clicking "Text 2," the initial display of "FLAG 1" is set to none, and the background color of "DOT" should change. The association between the t ...

The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit and I have a controller that combines both the view and edit functionalities: ... if ($routeParams.id) { $scope.itemId = $routeParams.id; $scope.editMode = true; Item.getB ...

Personalize the File upload with HTML and Javascript

https://jsfiddle.net/yugxqopz/ I'm new to the world of UI and have a simple request: 1) I want to upload a document using an "attach file" option 2) Once the file is selected, I want to automatically trigger a specific JavaScript function as shown ...

Unexpected appearance of DOM elements

I've come across an unusual bug in a web application I've been developing that is reproducible in Chrome and Safari, but not in Firefox. To witness the bug, go to www.lastcalc.com and type a single uppercase letter. The letter will be immediatel ...

Javascript program to validate if the user input matches a single value in an array

Currently, I am working with an array: var something = ["1","2","3","4"] ; My plan is to prompt the user to select a number. If the chosen number matches any value in the array, I want to trigger a specific action. Here's my dilemma: How can I veri ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

JavaScript fails to accurately arrange list items

Within my array of objects, I have a list of items that need to be sorted by the fieldName. While the sorting generally works fine, there are certain items where the sorting seems off and does not function properly. Here is the code snippet responsible fo ...

After ReactDOM is used, the JavaScript code is no longer functioning properly

While working on my latest project, I utilized react.js and encountered an issue where javascript seemed to stop working when using ReactDOM to render a class extended from React.Component. I noticed that the alert() method would not work if it was placed ...

Strange transparency glitch in Three.js

I've run into a perplexing issue while creating a 3D model for my website. One of the character's arms appears to be transparent, but only partially - you can see inside it. Here's what I'm talking about: Transparent arm. I've trie ...

Is there a way to share another person's contact card using whatsapp-web.js?

Is it possible to send a contact card of someone else using whatsapp-web.js, even if the person is not saved in my phone's contact list? I want to send a contact card to someone who is on my phone's contacts, but the contact information I want to ...

Load Jquery hover images before the users' interactions

Currently, I am in the process of creating a map of the United States. When hovering over any specific state, my goal is to replace the image with one of a different color. The issue I am encountering lies in the fact that the image gets replaced and a ne ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Using app.use in Express/node.js for routing causes the client to experience excessive delays

After setting up the server-side code in app.js, I encountered an issue: console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works. var express = require("expre ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

Use the fetch method to send a request from an HTML file that is being served through a

In my current setup, I have this code snippet to serve an HTML file via Go server. func main() { http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { path := r.URL.Path if path == "/" { pa ...

Building an accordion collapse feature in HTML using CSS and JavaScript

I've been working on creating an accordion interface, but I'm facing an issue where only the first collapsible button works properly. The rest of the buttons are not functioning and don't even appear on the page. When I remove the CSS styli ...

How can I insert an HTML link in PHP when encountering a die condition?

I am seeking a way to incorporate this link using JavaScript onclick function without the need for a button, <a href="#bot" onclick="startApp('ur')" img src="urBtn.png" /a> Additionally, I want it to execute during a PHP POST action utili ...

transforming numbers to text using ajax

Below is the AJAX code I am using to update passwords in my database table: $.ajax({ type: 'POST', url: root_url + '/services/services.php?method=updatesubpwd', data: { 'sid': ptcid, 'pwd&ap ...