Cycle through an array of elements and generate a fresh object

Here is an array of objects:

[
  {id:1,val: 5,name: 'Josh'},
  {id:2,val: 7,name: 'John'},
  {id:3,val: 6,name:'mike'},
  {id:4,val: 7,name: 'Andy'},
  {id:5,val: 8,name: 'Andrew'},
  {id:6,val: 7,name: 'Dave'}
]

I need to extract the id's with same val field into one array and remove duplicate objects.

[
  {id:1,val: 5,name: 'Josh'},
  {id:3,val: 6,name: 'Mike'},
  {id:5,val: 8,name: 'Andrew'},
  {id:[6,4,2],val: 7,name: ['Dave','Andy','John']}
]

Answer №1

@Tanjore, it would be beneficial for you to organize your ids within an object structure like this.

For all the ids with the value of 5, which is 1, you can use {'5': [1]}.

Similarly, for ids with the value of 6, which is 3, you can utilize {'3': [3]}.

And for ids with the value of 7, encompassing 2, 3, 4, you can structure it as {'7': [2, 3, 4]}.

...

You can establish an object resembling this format:

{
    "5": [
        1
    ],
    "6": [
        3
    ],
    "7": [
        2,
        4,
        6
    ],
    "8": [
        5
    ]
}

To achieve this object in a Node REPL environment, follow the steps below:

> var arr = [
...   {id:1,val: 5,name: 'Josh'},
...   {id:2,val: 7,name: 'John'},
...   {id:3,val: 6,name:'mike'},
...   {id:4,val: 7,name: 'Andy'},
...   {id:5,val: 8,name: 'Andrew'},
...   {id:6,val: 7,name: 'Dave'}
... ]
undefined
>
> var obj = {}
undefined
>
> arr.forEach((item) => {
... if (obj[item['val']] === undefined) {
..... obj[item['val']] = [item['id']];
..... } else {
..... obj[item['val']].push(item['id']);
..... }
... })
undefined
>
> obj
{ '5': [ 1 ], '6': [ 3 ], '7': [ 2, 4, 6 ], '8': [ 5 ] }
>
> JSON.stringify(obj, undefined, 4)
'{\n    "5": [\n        1\n    ],\n    "6": [\n        3\n    ],\n    "7": [\n        2,\n        4,\n        6\n    ],\n    "8": [\n        5\n    ]\n}'
>
> console.log(JSON.stringify(obj, undefined, 4))
{
    "5": [
        1
    ],
    "6": [
        3
    ],
    "7": [
        2,
        4,
        6
    ],
    "8": [
        5
    ]
}
undefined
>

Finally, by implementing the above approach, you will obtain the desired array structure as illustrated below:

[
    {
        "id": 1,
        "val": 5,
        "name": "Josh"
    },
    {
        "id": 3,
        "val": 6,
        "name": "mike"
    },
    {
        "id": [
            2,
            4,
            6
        ],
        "val": 7,
        "name": [
            "John",
            "Andy",
            "Dave"
        ]
    },
    {
        "id": 5,
        "val": 8,
        "name": "Andrew"
    }
]

Feel free to refer to the code snippet provided below to generate the desired array structure:

// Input array
var arr = [
    {id:1,val: 5,name: 'Josh'},
    {id:2,val: 7,name: 'John'},
    {id:3,val: 6,name:'mike'},
    {id:4,val: 7,name: 'Andy'},
    {id:5,val: 8,name: 'Andrew'},
    {id:6,val: 7,name: 'Dave'}
]

// Empty array for resulting data and easier grouping based on 'val'
var obj = {};

arr.forEach((item) => {
    if (obj[item['val']] === undefined) {
        obj[item['val']] = item;
    } else {
        var id = obj[item['val']]['id'];
        var name = obj[item['val']]['name'];

        if(typeof id === 'number'){
            obj[item['val']]['id'] = [id, item['id']];
            obj[item['val']]['name'] = [name, item['name']];
        } else { // 'object'
            obj[item['val']]['id'].push(item['id']);
            obj[item['val']]['name'].push(item['name']);
        }
    }
})


var newArr = Object.values(obj);
// console.log(newArr);

// Beautify the resulting array
console.log(JSON.stringify(newArr, undefined, 4));

/*
    [
        {
            "id": 1,
            "val": 5,
            "name": "Josh"
        },
        {
            "id": 3,
            "val": 6,
            "name": "mike"
        },
        {
            "id": [
                2,
                4,
                6
            ],
            "val": 7,
            "name": [
                "John",
                "Andy",
                "Dave"
            ]
        },
        {
            "id": 5,
            "val": 8,
            "name": "Andrew"
        }
    ]
*/

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

creating an HTML table from JSON data using a specific key

In this json file, I am looking to create separate tables based on the IDs provided. For example, ID: "50" should be displayed in one table, while ID: "57" should be shown in another table within the same context. { "version": "5.2", "user_type": ...

Angular and Firefox are flagging the response from my OAuth call as incorrect, however, Fiddler is showing a different result

Currently, I am in the process of developing a Cordova application and require OAuth authentication with my Drupal backend. My main issue lies in obtaining a request token for this purpose. Despite receiving a 200 response indicating success, when inspecti ...

What are the steps to create a function that behaves like instanceof when given a string as input

Is there a way to achieve something similar to this? var isChild = isInstanceOf( var1, 'Constructor') so that it is equivalent to var isChild = (var1 instanceof Constructor) The challenge is that the function Constructor is not available in t ...

jQuery toggle functioning in one scenario, but failing in another

My experience with JS/Jquery is limited which might explain why I'm struggling with this. I am attempting to hide some text on a page and then make it visible again by clicking on a toggle link. The JavaScript code below is what I have been using. The ...

Converting MySQL DateTime to seconds in JavaScript from PHP

In my JavaScript code, I have implemented a countdown timer that relies on two variables. The first variable, currentDate, is converted to milliseconds and then has 10 minutes worth of milliseconds added to it. The second variable, d, stores the current da ...

Prevent the TOUCHMOVE event from being triggered when the finger is no longer touching the element but is still pressed down

I have a parent div with 4 child elements inside. I want to trigger the touchmove event when I touch one of the span elements and move my finger. However, if I move my finger outside of the current span element while still pressing, I want the event to st ...

Running Javascript code using Puppeteer, in conjunction with Node.js and Express framework

Presented here is the code snippet that opens a browser to extract specific items using JavaScript. var express = require('express'); var fs = require('fs'); var request = require('request'); var cheerio = require(' ...

Prevent a specific folder from being included in expressjs routing

When using my expressjs app, I load public assets like this: app.use(express.static(__dirname + '/public')); Afterwards, I redirect all requests to the index, where every path is handled by Backbone app.get('*', routes.index); I am ...

What is the process for placing API routes within the new app directory of Next.js?

If you have a test API located at: pages\api\accounts\login.js, and are currently exploring the new app folder, which is still in its experimental phase in Next.js (as of today). Are you wondering if it's feasible to transfer your logi ...

The process of including a property in Vue.JS

Looking to include this property on my button: uk-toggle="target: #id" The desired outcome is: <button uk-toggle="target: #id" type="button">Click</button> I'm trying to achieve this with Vue.JS but I'm facing some difficulties. H ...

Guide on updating a specific item in a JSON array using npm request

I am currently working on setting a value in a JSON array utilizing a PUT request with the request module, specifically targeting one of multiple main objects within the array. The structure is as follows: [ 0: { status: 'pending' ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

Heroku Environment causing SocketIO malfunction while it works perfectly in Localhost

While working on a chat program using NodeJS and SocketIO, I faced an issue when deploying it to Heroku Server. It turns out that SocketIO was not functioning properly in the Heroku environment. Upon checking the logs in Heroku, I found no relevant inform ...

What is the best way to dynamically populate a table with JSON data that is received from an API response?

Currently, I have a table that contains the FORM element: <table id="example" class="sortable"> <caption><h3><strong>Product inventory list</strong></h3></caption> <thead> <tr ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

Cypress 7: Dealing with the onRequest Problem in the cy.intercept Function

We encountered a situation where we needed to assert that a spinner was displayed during a request using the following code: The code functioned properly in Cypress 6.4.0 cy.intercept({ url: '*', onRequest: () => { cy.get('[data- ...

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

A guide on truncating a portion of a string within a PHP two-dimensional array

Given an array named $arr, the task is to trim each element from ['name'] to a specified length and then append additional characters. I successfully achieved this with a regular array, but encountered difficulties when working with a two-dimensi ...

Tips for integrating the Bootstrap 5 JS file (bootstrap.bundle.js) into Laravel 8

I have successfully integrated Bootstrap v5.1.0 into my Laravel 8 project using npm. Now, I am facing an issue with including bootstrap.bundle.js in my public/app.js. After installing popperjs, I added the following code to my resources/js/bootstrap.js: t ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...