JavaScript outputs an array containing a collection of objects

[
    {'id': 123, 'name': 'apples', 'total': 30},
    {'id': 541, 'name': 'oranges', 'total': 42},
    {'id': 300, 'name': 'bananas', 'total': 18}
]

How can I display the contents of this array in the following format:

Apples: 30
Oranges: 42
Bananas: 18

I attempted

let myArray = [{
    'id': 123,
    'name': 'apples',
    'total': 30
  },
  {
    'id': 541,
    'name': 'oranges',
    'total': 42
  },
  {
    'id': 300,
    'name': 'bananas',
    'total': 18
  }
]
console.log(JSON.stringify(myArray.map(a => a.name)))

however, this is not what I intended to achieve.

Answer №1

You can utilize the spread syntax along with Object.assign to efficiently create an object from an array.

const information = [{'id': 123, 'name': 'apples', 'total': 30},{'id': 541, 'name': 'oranges', 'total': 42},{'id': 300, 'name': 'bananas', 'total': 18}]

const capitalize = str => str[0].toUpperCase() + str.slice(1)
const outcome = Object.assign(...information.map(({name, total}) => ({[capitalize(name)]: total})))
console.log(outcome)

Answer №2

To successfully process each item in the array, you will need to iterate through it

let items = [{
    'id': 123,
    'name': 'apples',
    'total': 30
  },
  {
    'id': 541,
    'name': 'oranges',
    'total': 42
  },
  {
    'id': 300,
    'name': 'bananas',
    'total': 18
  }
]

items.forEach((item) => {

  // perform operations on data
  let id = item.id;
  let name = item.name;
  let total = item.total;

  console.log(`${name}: ${total}`);

  // or output in a div/form using innerHtml etc.
});

Answer №3

One way to achieve this is by implementing the following code snippet:

var items = [
    {'id': 123, 'name': 'apples', 'quantity': 30},
    {'id': 541, 'name': 'oranges', 'quantity': 42},
    {'id': 300, 'name': 'bananas', 'quantity': 18}
]

console.log(items.map(item => ({[item['name'].charAt(0).toUpperCase() + item['name'].slice(1)]: item['quantity']})));

Answer №4

Your list will look something along these lines:

var vegetables = [
    {'id': 123, 'name': 'carrots', 'quantity': 25},
    {'id': 541, 'name': 'broccoli', 'quantity': 38},
    {'id': 300, 'name': 'spinach', 'quantity': 20}
]

You can iterate through the array using a for loop.

for(i=0; i<vegetables.length; i++)

{
    console.log(vegetables[i].name + " : " + vegetables[i].quantity);
}

This will give you the desired output.

https://i.sstatic.net/wfNxC.png

Answer №5

here is another way to achieve the same result

const list=[
    {'id': 987, 'name': 'grapes', 'total': 25},
    {'id': 456, 'name': 'pears', 'total': 36},
    {'id': 789, 'name': 'cherries', 'total': 50}
]

const updatedList=Object.assign(...list.map(item=> ({[item.name.charAt(0).toUpperCase() + item.name.slice(1)]:item.total})))

console.log(updatedList);

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

React Native: Changing Props Triggers Touch Event Cancellation

I am currently utilizing the react-native-gesture-handler library to construct a drag-and-drop sortable array of components. As I progress in the development, I am now focusing on incorporating animations into the functionality. To achieve this, I utilize ...

Nonlinear Scaling in D3.js Line Chart

My task is to generate a line chart where the y-axis domain ranges from 1.01 to 1000. The tick values change at the following intervals along the axis: 1.01 to 2, tick = 0.01 2 to 3, tick = 0.02 3 to 4, tick = 0.05 4 to 6, tick = 0.1 6 to 10, tick = 0.2 ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Create a unique Bootstrap 5 carousel featuring a single progress bar

Hey guys, I'm having some trouble with my Bootstrap 5 carousel. I want to add a progress bar with left and right arrows, and also the number of slides displayed, just like in this image: https://i.sstatic.net/pqOMy.jpg I did some research and found ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

Next.js presents a challenge with micro frontend routing

In the process of developing a micro frontend framework, I have three Next.js projects - app1, app2, and base. The role of app1 and app2 is as remote applications while base serves as the host application. Configuration for app1 in next.config.js: const ...

Can you explain the significance of module.exports? And what is the reasoning behind naming it "module"?

I have another question in regards to learning express as a beginner. Can anyone recommend any helpful websites for someone new to this technology? I find that the official documentations can be quite unclear and overwhelming at times for beginners. Any ...

A potential issue of a race condition may arise with the cursor when utilizing Promise.all

Currently, in the project I am working on that utilizes nodejs and mongo, there is a particular function that accepts a query and returns a set of data based on the limit and offset parameters provided. Additionally, this function also includes a total cou ...

What steps are required to add a basic Java 'class' instance representing a jQuery implementation in jQuery?

In my JavaScript code, I have a class named Caption: function Caption { var ... function get...() { } function set...(...) { ... } return( { get...: get... , set...: set... }); } This is just a part of t ...

What is the most efficient way to loop through nested JSON using jQuery in one go?

I have a substantial JSON file containing a snippet of the data shown below. The values used in the snippet are placeholders for this specific query. "restaurants":[ "name": "Burger King", "location": "Seattle, WA", "la ...

Exporting from Blender to three.js can sometimes result in misaligned object positions

Currently, I am encountering a challenge while exporting a basic scene from Blender to Three.js. Apart from the ongoing struggle with the texture not displaying properly, I have discovered an odd issue with the positioning of objects. The image below showc ...

Retrieve JSON information by utilizing variable string interpolation

Why is it that when I try to access an integer stored under id's/keys in a JSON object, the code doesn't work on its own? var rooms = { 'kitchen': [7, 40, 36, 16], 'livingroom': 31, 'livingroom2': 15, ...

AJAX call error: Invocation not permitted

I'm currently working on a web application using JQuery that requires communication with a server. I've reused this code multiple times, only changing the data and success function. However, every time I execute this function, I encounter an err ...

Encountering a Mongoose issue while attempting to load model files from a separate Mean.js project using the require function

I am currently working on a Mean.js project and in the process of familiarizing myself with this environment. To conduct some experiments, I created a parallel project for testing purposes in a separate folder where I am not using the Mean.js framework but ...

Is it possible for Node.js to execute individual database operations within a single function atomically?

As I delve into writing database queries that operate on node js, a puzzling thought has been lingering in my mind. There seems to be a misunderstanding causing confusion. If node is operating in a single-threaded capacity, then it follows that all functi ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

applying multiple conditions to filter data in javascript

I have been working on filtering data based on input, and it is functioning well. However, I am looking to add an additional condition to the filter. I want it to return if either the title or another value (such as sendFrom) is provided. const newData = ...

Determine the daily volume of emails sent from the "no-reply email" address using the Nodemailer library

Our company currently utilizes Nodemailer for internal email communication. Lately, we have been encountering issues with exceeding our daily SMTP relays, resulting in some emails failing to send. To investigate further, I have been tasked with monitoring ...

Can you explain the purpose of FunctionConstructor in typeScript?

As I delved into the Typescript Ecmascript source code, I stumbled upon this intriguing snippet: interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: st ...