Ways to combine multiple items into a single object using underscore

Looking to transform this data:

[
  {name: 'foo', type: 'product'},
  {name: 'bar', type: 'product'},
  {name: 'john', type: 'product'},
  {name: 'no name', type: 'product'},
]

Is there a way to categorize and extract all objects excluding those with name:'no name' into separate groups like so:

{  
  0:[
    {name: 'foo', type: 'product'},
    {name: 'bar', type: 'product'},
    {name: 'john', type: 'product'}
  ],

  1:[
    {name: 'no name', type: 'product'},
  ]
}

Answer №1

For creating an object with keys 0 and 1, you can utilize the _.groupBy function:

var objResult = _.groupBy(data, function(d) { return +(d.name === "no name") })

If you want to generate an array with two elements (also with keys 0 and 1), you have the option to use _.partition (Underscore 1.6.0 +):

partition_.partition(array, predicate)
: Split the array into two arrays: one containing elements that satisfy the predicate and another containing elements that do not satisfy it.

var arrResult = _.partition(data, function(d) { return d.name !== "no name" })

JSBin

Answer №2

When comparing the two, it is worth noting that plain ECMAScript requires only a slightly longer code snippet:

data.reduce(function(acc, obj) {
  acc[obj.name == 'no name'? 1:0].push(obj);
  return acc;},{0:[],1:[]}
);

Answer №3

Check out this link for more information on how to use the groupBy function from Underscore.js:

var items = [
  {name: 'apple', category: 'fruit'},
  {name: 'carrot', category: 'vegetable'},
  {name: 'banana', category: 'fruit'},
  {name: 'broccoli', category: 'vegetable'}
]

var groupedItems = _.groupBy(items, function(item) { return item.category == 'fruit' ? 'fruits' : 'vegetables'; })

console.log(groupedItems)

Answer №4

Give it a shot that way.

let items = [
 {label: 'apple', category: 'fruit'},
 {label: 'carrot', category: 'vegetable'},
 {label: 'banana', category: 'fruit'},
 {label: 'tomato', category: 'vegetable'},
];

let categorizedItems = _.groupBy(items, function (item) { 
 return item.label == 'tomato' ? 1 : 0;
});

Answer №5

What are the benefits of using a framework for something as simple as this? Here is a JavaScript solution that effectively groups elements by a specified property, making it convenient to manipulate the resulting object.

var elements=[
  {name: 'foo', type: 'product'},
  {name: 'bar', type: 'product'},
  {name: 'john', type: 'product'},
  {name: 'no name', type: 'product'},
  {name: 'foo', type: 'product'},
  {name: 'bar', type: 'product'},
  {name: 'john', type: 'product'},
  {name: 'no name', type: 'product'},
  {name: 'no name', type: 'product'},
  {name: 'no name', type: 'product'},
  {name: 'no name', type: 'product'},
];        

function groupByProperty(propName, elements) {
var groupedItems = {};
for (var i = 0, length = elements.length; i < length; i++) {
    var item = elements[i];
    var value = item[propName].trim();
    var group = groupedItems[value];
    if (group === undefined) {
        group = [item];
        groupedItems[value] = group;
    } else {
        group.push(item);
    }
}
return groupedItems;
}

var results = groupByProperty('name',elements);

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

What is the process of importing schema and resolvers in GraphQL-Yoga or Node?

After discovering that graphql-yoga V1 is no longer supported, I'm aiming to upgrade to graphql-yoga/node V2. Although I've reviewed the official documentation on the website, I'm encountering difficulties in migrating from V1 to V2. Is it ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

Combining 2 objects in vue.js that share a common field name

Currently, I am attempting to merge two objects based on a shared key, specifically when they have two fields with the same name but differing values. var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : &quo ...

Grab and drop into place

I have been searching for solutions, but so far I haven't found anything that works for my specific case. I have an upload button that currently works on a click event, but I also want it to be able to drag and drop files for uploading. Here is the H ...

Is scanf capable of handling massive char arrays without breaking?

I am encountering an issue with reading a string of triple digit-digit-space. Below is the relevant code snippet, which may or may not require additional libraries: #include <stdio.h> #include <stdlib.h> #define N 20 #define M 20 #define n (3 ...

Ways to soften a section of a canvas component?

What is the simplest way to apply a blur effect to a specific portion of my canvas element? I am utilizing the JavaScript 3D Library known as three.js. This library simplifies the use of WebGL. While they offer examples of blur and depth of field effects, ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Unable to utilize JavaScript from the imported AJAX page XMLHttpRequest

I have implemented a bit of AJAX functionality using XMLhttpRequest, where it replaces a div and functions as expected. However, I am facing difficulty in getting the JavaScript code in the included AJAX page to execute. Is there a way to run JavaScript f ...

Utilizing exponential formatting for Plotly axis scales

Following up on a previous question here: SO Q The solution provided in the previous question uses JavaScript code to convert axis ticks into exponential format, but it only works for a single axis on a single plot. When applied in a subplot() structure, ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> https://i.sstatic.net/d ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

The onClick function designed to trigger the Material UI dialog box is experiencing functionality issues

Is there a bug in the component? The material-ui dialog-box sometimes pops up on button click and shows the target value perfectly, but other times it doesn't. I am passing the value on the icon onclick event - (e) and using it in the onClick function ...

How to utilize variables in Angular module functions?

My experience with Angular is fairly new, and I recently encountered a debugging issue in my application that unfolded like this: Imagine I am adding a new directive to an existing module defined in another .js file. When I tried using the syntax below: ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

Ways to display a tooltip on a listbox that can be moved

My ASPX page contains the following control: <asp:ListBox ID = "X" runat="Server" CssClass = "listbox"></asp:ListBox> I need to display a tooltip on each list item, as they are movable and their positions can be c ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

How can I obtain the coordinates when the mouse enters Vue?

Trying to create an animation triggered by the mouseenter event in Vue, I ran into a roadblock - obtaining the coordinates of the sections. <script setup> function fetchCoordinates(e) { const coords = { x: e.clientX, y: e.clientY } // This seems to ...