merging values from objects within an array

My goal is to merge all the important values from the objects in this array.

var currentInventory = [
  {
    name: 'Brunello Cucinelli',
    shoes: [
      {name: 'tasselled black low-top lace-up', price: 1000},
      {name: 'tasselled green low-top lace-up', price: 1100},
      {name: 'plain beige suede moccasin', price: 950},
      {name: 'plain olive suede moccasin', price: 1050}
    ]
  },
  {
    name: 'Gucci',
    shoes: [
      {name: 'red leather laced sneakers', price: 800},
      {name: 'black leather laced sneakers', price: 900}
    ]
  }
];

The desired output should be:

[
 ['Brunello Cucinelli', 'tasselled black low-top lace-up', 1000],
 ['Brunello Cucinelli', 'tasselled green low-top lace-up', 1100],
 // ...
]

I have written the following code:

function renderInventory(inventory) {
  const arr = [];
  for (var i = 0; i < inventory.length; i++) {
    for (var n = 0; n < inventory[i].shoes.length; n++) {
      arr.push([inventory[i].name + ', ' + inventory[i].shoes[n].name + ', ' + inventory[i].shoes[n].price]);
    }
  }
  return arr;
}

Unfortunately, it currently gives me:

[
 ['Brunello Cucinelli, tasselled black low-top lace-up, 1000'],
 ['Brunello Cucinelli, tasselled green low-top lace-up, 1100'],
...
]

I'm unsure how to adjust my code so that each element is wrapped in quotations, rather than the entire array.

Answer №1

Ensure that your function returns an array with individual items, not a concatenated string.

arr.push([inventory[i].name, inventory[i].shoes[n].name,  inventory[i].shoes[n].price]);

function organizeInventory(inventory) {
  const arr = [];
  for (var i = 0; i < inventory.length; i++) {
    for (var n = 0; n < inventory[i].shoes.length; n++) {
      arr.push([inventory[i].name, inventory[i].shoes[n].name,  inventory[i].shoes[n].price]);
    }
  }
  return arr;
}

var currentStock = [{ name: 'Brunello Cucinelli', shoes: [{ name: 'tasselled black low-top lace-up', price: 1000 }, { name: 'tasselled green low-top lace-up', price: 1100 }, { name: 'plain beige suede moccasin', price: 950 }, { name: 'plain olive suede moccasin', price: 1050 }] }, { name: 'Gucci', shoes: [{ name: 'red leather laced sneakers', price: 800 }, { name: 'black leather laced sneakers', price: 900 }] }];

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

A more concise method by using destructured values.

function organizeInventory(inventory) {
    return inventory.reduce((r, { name: item, shoes }) => [
        ...r,
        ...shoes.map(({ name, price }) => [item, name, price])
    ], []);
}

var currentStock = [{ name: 'Brunello Cucinelli', shoes: [{ name: 'tasselled black low-top lace-up', price: 1000 }, { name: 'tasselled green low-top lace-up', price: 1100 }, { name: 'plain beige suede moccasin', price: 950 }, { name: 'plain olive suede moccasin', price: 1050 }] }, { name: 'Gucci', shoes: [{ name: 'red leather laced sneakers', price: 800 }, { name: 'black leather laced sneakers', price: 900 }] }];

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

Answer №2

You can utilize the flatMap function to extract the name and corresponding shoes array from each outer object:

var currentInventory = [
  {
    name: 'Brunello Cucinelli',
    shoes: [
      {name: 'tasselled black low-top lace-up', price: 1000},
      {name: 'tasselled green low-top lace-up', price: 1100},
      {name: 'plain beige suede moccasin', price: 950},
      {name: 'plain olive suede moccasin', price: 1050}
    ]
  },
  {
    name: 'Gucci',
    shoes: [
      {name: 'red leather laced sneakers', price: 800},
      {name: 'black leather laced sneakers', price: 900}
    ]
  }
];
const output = currentInventory.flatMap(
  ({ name, shoes }) => shoes.map(
    shoe => [name, shoe.name, shoe.price]
  )
);
console.log(output);
<script src="https://polyfill.io/v3/polyfill.min.js?features=default%2CArray.prototype.flatMap"></script>

Answer №3

Learn more about Array.prototype.reduce(), Array.prototype.map() as well as Array.prototype.concat():

const currentStock = [{name: 'Calvin Klein',clothes: [{name: 'black slim-fit dress shirt', price: 50},{name: 'navy blue chinos', price: 40}]},{name: 'Tommy Hilfiger',clothes: [{name: 'striped polo shirt', price: 30},{name: 'khaki cargo shorts', price: 35}]}];
const inventoryResult = currentStock.reduce((prev, curr) => [].concat(prev, curr.clothes.map(item => ([curr.name, item.name, item.price]))), [])

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

Answer №4

To start, gather all sub-array shoes and flatten them out. Then utilize the map function to structure them as desired.

Below is the code snippet:

const currentInventory = [
  {
    name: "Brunello Cucinelli",
    shoes: [
      { name: "tasselled black low-top lace-up", price: 1000 },
      { name: "tasselled green low-top lace-up", price: 1100 },
      { name: "plain beige suede moccasin", price: 950 },
      { name: "plain olive suede moccasin", price: 1050 }
    ]
  },
  {
    name: "Gucci",
    shoes: [
      { name: "red leather laced sneakers", price: 800 },
      { name: "black leather laced sneakers", price: 900 }
    ]
  }
];

const flatten = currentInventory
  .reduce((flat, inventory) => {
    flat.push(inventory.shoes);
    return flat;
  }, [])
  .flat();

const result = flatten.map(({ name, price }) => {
  return [name, price];
});

console.log(result);

Concise version:

const result = currentInventory
  .reduce((flat, { shoes }) => {
    flat.push(shoes);
    return flat;
  }, [])
  .flat()
  .map(({ name, price }) => [name, price]);

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

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Exploring the possibilities with Node.js and OpenCV

I'm experiencing difficulties with face tracking and detection using the npm opencv package. Right now, I'm attempting to draw a circle around each detected face. Below are the error details and associated files. I'm unsure if it's a b ...

Experiment with a ThreeJS, Websockets, and NodeJS Client/Server Interaction

Exploring the possibilities of socket.io, ThreeJS, Javascript, and NodeJS, I embarked on a project to create a simple client/server setup using ThreeJS's graphics. While uncertain if these frameworks would seamlessly integrate, I decided to take a cha ...

Ways to conceal #div element from displaying in the href attribute within the anchor tag

My anchor tag has an href attribute that looks like this: <a onclick='loadReview(\"" + strexternalURL + "\");' href='#productName1'. When clicking on it, the URL appears as http://localhost:54986/Dealerlist.aspx#productName ...

Is it necessary to validate, sanitize, or escape data before utilizing the build method in sequelize.js?

I currently have a node/express/sequelize application where I am utilizing the build method in sequelize to generate instances of my foo model. Foo Controller exports.create = function(req, res) { var foo = db.Foo.build(req.body); foo.save().t ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

Using jQuery in an external JavaScript file may encounter issues

As a newcomer to jQuery, I decided to try writing my jQuery code in an external js file rather than embedding it directly into the head of the HTML file. Unfortunately, this approach did not work as expected. Here is what my index.html looks like: < ...

Leverage Async/Await in React.js with the Axios Library

Recently, I came across an interesting article on Medium titled How to use async/await with axios in react The article discussed making a simple GET request to a server using Async/Await in a React.js App. The server returned a JSON object at /data with t ...

Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priori ...

What could be causing the axesHelper function to not display the axis on the screen?

I encountered an issue with my code while working with three.js. I am having trouble initializing certain components and objects such as the axis and cube, as they are not displaying on the screen. Can someone please help me identify where the error migh ...

Best method for extracting content from a tag and storing it in a variable in a Vue component

Looking for the best way to capture user-clicked {{exchange}} in a Vue code snippet <ul> <li v-for="exchange in finalExchanges"><button class="resultBtn"> {{exchange}} <hr></button></li> </ul> The JavaScrip ...

Execute an ajax request when the document is fully loaded using jQuery

Retrieve Cities in Japan using Ajax $(document).ready(function() { $.ajax({ type: 'POST', url: '../include/ListOfCities.php', dataType: "json", data: { Country: "Japan" }, ...

Tips for dividing the rows within an array using the match() function?

Within my matrix are arrays of rows. let matrix=[['hello'],['world']]; I am looking to duplicate each row within the matrix. matrix=matrix.map(x=>String(x).repeat(2)).map(x=>x.match(new RegExp??)) The desired outcome should be [ ...

Organize values according to property values and display them using JavaScript

I have a unique array structure that is as follows: var array = [[ { "location": {} }, { "distance": 6.4 }, { "zip1": "06120" }, { "zip2": "06095" }, { "group": 1 }, { "weight": 1119 } ], [ { "location": {} }, { "distance": ...

Tips for utilizing my fiddle for subsequent data entry by incorporating new elements into the environment using three.js

Whenever I input a number for the second, third, etc. time in the textbox, I want to remove old objects and add new ones. Basically, I need to delete existing objects from the scene and then introduce new objects based on the new input. I have tried variou ...

Is the `key` function in React.js Tic-Tac-Toe truly effective in improving performance?

Check out the updated version of the React tic-tac-toe game on CodePen In this version, I've included time in the move description to track when each li element was rendered: <li key={move}> <button onClick={() => this.jumpTo(move)}> ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

if a user does not click on an element in jQuery

Looking for a clever jQuery trick to determine if something other than a specific element (and its descendants) was clicked? <body> <header></header> <p>stuff<p> <div class="floating-form"> <form>more st ...

Is there a way to incorporate a numerical value into the legend of my morris.js donut chart?

I'm utilizing multiple morris.js charts that are populated from my databases based on specific search terms. The challenge I'm facing is adding both a number and text to the legend of my donut charts. Although the code works fine, I encountered a ...