The function loops through an array of objects and combines specific properties from the objects into a single string

I am currently working on creating a unique custom function that will loop through an array of objects and combine selected object property keys into a single string separated by commas.

Let me explain using some code:

var products = [
  {
    "id": 1,
    "variants": {
      "colour": "black"
    },
  },
  {
    "id": 2,
    "variants": {
      "colour": "red"
    }
  }
];

function joinedByComma(arr, keys) {
  // code will go here
}

joinedByComma(products, ["variants", "colour" ]);
// expected output is "black,red"

Can anyone provide suggestions or guidance on how to implement the joinedByComma function? The length of the array passed in the second parameter can vary based on the depth of the object...

Answer №1

 function combineByComma(arr, keys) {
   return arr.map(element => keys.reduce((obj, key) => obj[key] || {}, element)).join();

Simply map each entry in the array by reducing the keys to the object's value, then join them together with a comma.

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

Extracting the toArray value from the sortable() function

It feels like I must be making a simple mistake here, as this seems like such a basic issue. The problem I'm facing involves using the sortable() function on a short list and wanting to retrieve an array of the sorted list's IDs. While my code a ...

Tips for implementing arraybuffer playback in video tags

I have been exploring ways to convert images from an HTML canvas into a video. After much research, I just want to be able to select a few images and turn them into a video. By passing multiple images to a library engine, I am able to receive an array buff ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

Save the text entered into an input field into a Python variable

Is there a way to retrieve the text from input fields that do not have a value attribute using Selenium? The issue is that these fields are populated automatically, possibly through JavaScript, upon page load and the text does not appear in the HTML source ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

Tips for formatting arrays in PHP

My array contains the following data: Array ( [0] => Array ( [Import] => Array ( [id] => 1 [category_id] => 2 [product_id] => 2 ...

Implementation of isalpha in C

Hey there! I decided to have some fun by creating my own version of the isalpha function. Surprisingly, it seems to work, but unfortunately I'm getting a bunch of warnings. Can anyone help me figure out how to fix them or suggest a better approach? H ...

Utilizing the power of Vue.js version 2.x alongside the sleek features of Bootstrap

I'm currently experimenting with incorporating Bootstrap 5 into Vue (2.x) without relying on any third-party libraries. My approach involves creating a custom wrapper for select Bootstrap components that I intend to utilize. For guidance, I've b ...

Ways to retrieve the values from a numpy array employing an array that includes the index numbers I wish to retrieve

Let's say I have two numpy arrays. The first one, named idxes, includes the indices of elements that I want to extract from another array called arr. arr = ['a', 'b', 'c' ] idxes = [1, 2] // This is the desired result re ...

Having trouble positioning a div in AngularJS so that it stays pixel-perfect regardless of browser resize or device orientation? Unfortunately, it's

I am a newcomer to AngularJS and have been struggling with a particular issue for several days now, leading me to suspect that I may be using it incorrectly. The problem at hand involves positioning 30 divs in a specific manner: 1) Each div should displa ...

In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object type MyType = 'name' | 'base' | 'six'; obj: MyType = { 'name': {key: 'm1'}, 'base': {key: 'm2'}, 'six': {key: 'm3'}, } My goal is ...

Combining objects within an array based on shared key values

Is there a way to merge objects with the same date into one cohesive data set? I could use some guidance. const info = [ { date: '1 Day', green: 35 }, { date: '2 Day', green: 64 }, { date ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

Discover and eliminate nested levels

How can I locate and delete a specific value with the ID "5cc6d9737760963ea07de411"? Data: [ { "products" : [ { "id" : "5cc6d9737760963ea07de411", "quantity" : 1, "totalPrice" : 100, ...

What is the best way to use Shadcn to incorporate a calendar that takes up half of my website?

Currently, I am in the process of developing a scheduling appointment system. My main challenge is getting the calendar to take up half of my page's space. Despite my attempts to adjust its height and width, I have not been successful in seeing any ch ...

Compare the times and find the intersection time

There is an array that contains start and end times: Array ( [0] => Array ( [starttime] => 08:00 [endtime] => 9.30:00 ) [1] => Array ( [starttime] => 10:00 [en ...

What is the best way to separate a JSON decoding file in PHP based on key/value pairs?

I am venturing into PHP coding for the first time, and I have come across a json file (see screenshot). json file Within this file, there exists a name alongside an array of sources. My task is to dissect this "sources" array according to its fields (name ...