Combine items based on their keys and corresponding values

The original question has been updated for clarity. The desired output is to merge an array of objects into a single object with specific conditions.

I am attempting to consolidate three sets of keys per object into one instance, choosing the lowest number for the Rank value or '-' if all Ranks are '-'

Below is sample data:


let objs = [
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'Second Rank': '-',
    'Third Rank': 1,
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'Second Rank': 2,
    'Third Rank': '-',
  },
  {
    Keyword: 'A keyword',
    'First Rank': '-',
    'Second Rank': '-',
    'Third Rank': 7,
  }
]

// Code to filter and merge the objects...

Currently struggling to include objects with no values in the final merged result. Desired output shown below:

{
  'Keyword': 'A keyword',
  'First Rank': '-',
  'Second Rank': 2,
  'Third Rank': 1,
}

Any suggestions on how to achieve this? Thank you!

Answer №1

Why not give this a try?

let objects = [
  {
    'Keyword': 'A keyword',
    'First URL': '-',
    'First Rank': '-',
    'First Title': '-',
    'Second URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Third URL': '-',
    'Third Rank': '-',
    'Third Title': '-'
  },
  {
    'Keyword': 'A keyword',
    'First URL': '-',
    'First Rank': '-',
    'First Title': '-',
    'Second URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Third URL': 'https://example.com',
    'Third Rank': 7,
    'Third Title': 'Title'
  },
  {
    'Keyword': 'A keyword',
    'First URL': '-',
    'First Rank': '-',
    'First Title': '-',
    'Second URL': 'https://example.com',
    'Second Rank': 11,
    'Second Title': 'Title',
    'Third URL': '-',
    'Third Rank': '-',
    'Third Title': '-'
  },
  {
    'Keyword': 'A keyword',
    'First URL': '-',
    'First Rank': '-',
    'First Title': '-',
    'Second URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Third URL': 'https://example.com',
    'Third Rank': 1,
    'Third Title': 'Title overwritten'
  },
]


var output = objects.slice().reduce((accumulator, item, index) => {
  resultItem = accumulator.find(accItem => accItem['Keyword'] === item['Keyword']);
  if (!resultItem) {
    accumulator.push(item)
  } else {
    Object.keys(resultItem).map(k => {
      if (item[k] !== '-') {
        if (typeof item[k] === 'number') {
          resultItem[k] = resultItem[k] === '-' ? item[k] : Math.min(item[k], resultItem[k]);
        } else {
          resultItem[k] = item[k];
        }
      }
    })
  }
  return accumulator;  
}, []);

console.log(output);

Answer №2

To streamline the process, you can utilize the reduce function and then within the handler, inspect the numerical value to determine which is lower among the two values.

Noteworthy in this code excerpt is the introduction of an extra object with Third Rank = 1.

let array = [{ Keyword: 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': '-', 'Second Rank': '-', 'Second Title': '-', 'Third URL': '-', 'Third Rank': '-', 'Third Title': '-' }, { Keyword: 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': '-', 'Second Rank': '-', 'Second Title': '-', 'Third URL': 'https://example.com', 'Third Rank': 7, 'Third Title': '2 third title' }, { Keyword: 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': 'https://example.com', 'Second Rank': 11, 'Second Title': '3 Second title', 'Third URL': '-', 'Third Rank': '-', 'Third Title': '-' }, { Keyword: 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': 'https://example.com', 'Second Rank': 11, 'Second Title': '3 Second title', 'Third URL': '-', 'Third Rank': 1, 'Third Title': '-' }], merged = array.reduce(({ ...r }, o) => { Object.entries(o).forEach(([k, v]) => { if (v !== '-') { if (isNaN(+v) || isNaN(+r[k])) r[k] = v; else r[k] = Math.min(+r[k], +v); } }); return r; }); console.log(merged);

Answer №3

To simplify the array, you can analyze the keys of each entry.

let array = [{ 'Keyword': 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': '-', 'Second Rank': '-', 'Second Title': '-', 'Third URL': '-', 'Third Rank': '-', 'Third Title': '-' }, { 'Keyword': 'A keyword', 'First URL': '-', 'First Rank': '-', 'First Title': '-', 'Second URL': '-', 'Second Rank': '-', 'Second Title': '-', 'Third URL': 'https://for-seven.example.com', 'Third Rank': 7, 'Third Title': 'Title' }, { 'Keyword': 'A keyword...
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Appreciation to all contributors who provided solutions to this query. However, I realized that I omitted certain requirements in my initial explanation and by the time I clarified them, it was too late to receive follow-up responses. Hence, I took matters into my own hands and devised a solution that, although functional, may not be the most optimal approach.

let objs = [
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 1,
    'Third Title': 'Title for 1',
    'Third URL': 'https://for-one.example.com'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': 2,
    'Second Title': 'Title for 2',
    'Second URL': 'https://for-two.example.com',
    'Third Rank': '-',
    'Third Title': '-',
    'Third URL': '-'
  },
  {
    'Keyword': 'A keyword',
    'First Rank': '-',
    'First Title': '-',
    'First URL': '-',
    'Second Rank': '-',
    'Second Title': '-',
    'Second URL': '-',
    'Third Rank': 7,
    'Third Title': 'Title for 7',
    'Third URL': 'https://for-seven.example.com'
  }
]

// Code logic for filtering and merging object data goes here

console.log(result)

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

Comparing strings in AngularJS

Struggling to compare two strings in AngularJS, I've come across various examples online. From what I understand, there are different methods like angular.equals(str1, str2), ===, and == if you're certain both are strings... Despite trying all t ...

An unusual outcome occurred while attempting to duplicate the text

After copying the letter A, I noticed that an empty string is being logged to the console instead of the expected A. However, when I paste, the console does successfully log the letter A. document.addEventListener('copy', handler); document ...

Learn how to gradually make text disappear and reappear using JavaScript or jQuery

I am a beginner in JavaScript and jQuery, and I am trying to achieve a text fade-out effect. Once the text has completely faded out, I want it to return with the same fade-in effect. I have been exploring if statements and fadeIn effects, but I am strugg ...

What is the reason behind Angular's continued use of JSON for encoding requests? (specifically in $http and $httpParamSerializerJ

Is there a way to set Angular to automatically send requests as x-www-form-urlencoded instead of JSON by default? Angular version 1.4.5 I've tried the following code snippet but it doesn't seem to work: angular.module('APP').config( ...

JavaScript in a copied style

When using JavaScript to copy a table cell, I encountered an issue where the style was not being copied along with the content. Attempting to directly assign the style from one cell to another did not work as expected. To ensure that the text-align proper ...

Steps to cancel an AJAX call in C# .NET:

In the ajax.cs class, I am calling methods from the javascript side. To register this on the default.aspx page load, I did the following: Ajax.Utility.RegisterTypeForAjax(typeof(ajax)); Occasionally, some methods take a long time to execute. In such case ...

Utilizing Vue to Transform Unicode Characters into HTML Elements

I have a scenario where an API response contains a Unicode string that needs to be displayed correctly in the view. Despite Vue treating it as a string and not automatically converting it to HTML, I believe JavaScript should handle the rendering process. ...

The Iframe is preventing the mousemove event from taking place

After attaching an event to the body, a transparent iframe mysteriously appeared in the background of the popup. I am attempting to trigger a mousemove event on the body in order for the popup to disappear immediately when the mouse moves over the iframe ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

Encountering a problem while retrieving JSON or XML data from a URL using jQuery AJAX

Here is a snippet of code that I've been working on: jQuery(document).ready(function(){ var user_key = "asdflk134"; var app_key = "pigasdb95r91bva"; var params = "app_key="+app_key+"&user_key="+user_key+"&format=xml"; jQuery ...

Guide to showcasing information interactively using ant design tables

My proficiency in JavaScript is not the best, but I am currently working on building a frontend using React. I have a table that I obtained from ant.design, and I am attempting to populate this table with data from my database. However, I am encountering d ...

The VueJs Method has the ability to directly alter a given response

Within my parent component, I am connecting to the backend using a query. Through interactions with the navbar and utilizing my activeView data in the parent component, I trigger the rendering of a new child page upon clicks and pass a prop from the respon ...

I am running into a problem trying to configure the "timezone" setting for MySQL within Sequelize and Node.js

Currently, I am utilizing node and sequelize to develop a web API. So far, everything is functioning correctly. However, when attempting to update the user table with the following code: var localDate=getDateTime(); console.log(localDate) //output: 2021/06 ...

Is it possible that the JqueryUI accordion effect fails to load after updating the content?

My list utilizes the accordion effect from JqueryUI and I have successfully swapped the content inside the list. However, after swapping the content, all the Jquery styling effects are lost. I researched on forums and found suggestions to destroy and re- ...

Promise.all() ensures that all promises in the array are resolved with the same value

Currently, I'm in the process of developing a module that contains a function designed to return a promise using Promise.all() for the purpose of sending emails to multiple users. By simplifying the code, I have managed to isolate and reproduce the is ...

What is the best method to add information into an array using Angular 7?

My data consists of an array of objects : [ { indicatorDatasource: "trackingError", un_an: 0, trois_ans: 0, cinq_ans: 0 }, { indicatorDatasource: "annualisedFundPerformance", un_an: 19.749642029434945, trois ...

Creating a versatile "add new entry" form in Angular that appends a new record to the parent scope

In my Angular application setup, I have an "Edit Invitation" state where a single invitation is scoped. This invitation contains a list of guests controlled by a guestList controller and iterated over in the view. <div ng-controller="guestListCtrl as g ...

Is there a specific reason why react-helmet does not automatically update the og meta tag?

I am currently working on generating dynamic og. Specifically, I have a detailed page featuring news on my website. When sharing a link to this page, it should generate the og data. Below is an excerpt of my code: <Helmet> <title>{info &a ...

Arranging items by specific criteria in ng-repeat for a personalized sorting experience

Within my controller, I have an object named $scope.addresscards. The JavaScript code is provided below: var myApp = angular.module('myApp', []); function MyCtrl($scope) { $scope.addresscards = { "work_address": { "location":"w ...