logo
down
shadow

Compare objects recursively and put duplicate key values into array


Compare objects recursively and put duplicate key values into array

By : jhui Lee
Date : October 22 2020, 08:10 AM
around this issue Since there are nesting keys that might be missing in some of the objects, you can merge them via lodash's _.mergeWith(), and collect duplicates into arrays:
code :
const a = {"first_name":"Tom","height":{"feet":5,"inches":0}}
const b = {"first_name":"Thomas","last_name":"Walsh","email":"tomwalsh@domain.com","height":{"feet":6,"inches":0}}
const c = {"email":"tomwalsh@sample.edu"}

const shouldCollect = (s) => _.negate(_.overSome([
  _.isUndefined,
  _.isObject,
  _.partial(_.eq, s)
]))


const mergeDupes = (...args) => _.mergeWith({}, ...args, (o, s) => {
  if(_.isArray(o)) return _.uniq([...o, s]);
  if(shouldCollect(s)(o)) return [o, s];
})

const result = mergeDupes(a, b, c)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
const a = {"first_name":"Tom","height":{"feet":5,"inches":0}}
const b = {"first_name":"Thomas","last_name":"Walsh","email":"tomwalsh@domain.com","height":{"feet":6,"inches":0}}
const c = {"email":"tomwalsh@sample.edu"}

const shouldCollect = (s) => _.negate(_.overSome([
  _.isUndefined,
  _.isObject,
  _.partial(_.eq, s)
]))

const omitNonDuplicates = obj =>
  _.transform(obj, (a, v, k) => {
    if (_.isArray(v)) a[k] = v;
    else if (_.isObject(v)) {
      const clean = omitNonDuplicates(v);
      if(!_.isEmpty(clean)) a[k] = clean;
      return;
    }
  });
  
const mergeDupes = (...args) => omitNonDuplicates(_.mergeWith({}, ...args, (o, s) => {
  if(_.isArray(o)) return _.uniq([...o, s]);
  if(shouldCollect(s)(o)) return [o, s];
}))

const result = mergeDupes(a, b, c)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


Share : facebook icon twitter icon
Compare Objects in Array and Remove Duplicate & Update - Javascript

Compare Objects in Array and Remove Duplicate & Update - Javascript


By : PavelPopravil
Date : March 29 2020, 07:55 AM
Does that help I have an array of objects that presents as follows: , Solved in the following manner:
1.) Verify object is not empty.
code :
if (o.ConsolidatedItem_quantity != '') {

    var result = $.grep(finalObject, function(e) {
        return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
    });
    if (result.length == 0) {...}
    else {
        finalObject.some(function (e) {
            if(e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber){
                var a;
                a = +e.ConsolidatedItem_quantity + +o.ConsolidatedItem_quantity;
                e.ConsolidatedItem_quantity = a.toString();
                document.getElementById(o.ConsolidatedItem_itemNumber).value=a;
                return true;
            };
        });
    }
}
How would I compare field values of two Java objects of the same but unknown type recursively?

How would I compare field values of two Java objects of the same but unknown type recursively?


By : user2655421
Date : March 29 2020, 07:55 AM
like below fixes the issue Disclaimer. I am the author of the JAXB2 Basics plugin package which includes the JAXB2 Equals plugin.
code :
public boolean equals(Object object) {
    final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
    return equals(null, null, object, strategy);
}

public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
    if (!(object instanceof PurchaseOrderType)) {
        return false;
    }
    if (this == object) {
        return true;
    }
    final PurchaseOrderType that = ((PurchaseOrderType) object);
    {
        USAddress lhsShipTo;
        lhsShipTo = this.getShipTo();
        USAddress rhsShipTo;
        rhsShipTo = that.getShipTo();
        if (!strategy.equals(LocatorUtils.property(thisLocator, "shipTo", lhsShipTo), LocatorUtils.property(thatLocator, "shipTo", rhsShipTo), lhsShipTo, rhsShipTo)) {
            return false;
        }
    }
    {
        USAddress lhsBillTo;
        lhsBillTo = this.getBillTo();
        USAddress rhsBillTo;
        rhsBillTo = that.getBillTo();
        if (!strategy.equals(LocatorUtils.property(thisLocator, "billTo", lhsBillTo), LocatorUtils.property(thatLocator, "billTo", rhsBillTo), lhsBillTo, rhsBillTo)) {
            return false;
        }
    }
    // ...
    return true;
}
    final EqualsStrategy strategy = new org.jvnet.hyperjaxb3.lang.builder.ExtendedJAXBEqualsStrategy() {

        @Override
        public boolean equals(ObjectLocator leftLocator,
                ObjectLocator rightLocator, Object lhs, Object rhs) {
            if (!super.equals(leftLocator, rightLocator, lhs, rhs)) {
                logger.debug("Objects are not equal.");
                super.equals(leftLocator, rightLocator, lhs, rhs);
                logger.debug("Left: "
                        + (lhs == null ? "null" : lhs.toString()));
                if (leftLocator != null) {
                    logger.debug("At [" + leftLocator.getPathAsString()
                            + "].");
                }
                logger.debug("Right: "
                        + (rhs == null ? "null" : rhs.toString()));
                if (rightLocator != null) {
                    logger.debug("At [" + rightLocator.getPathAsString()
                            + "].");
                }
                return false;
            } else

            {
                return true;
            }
        }

    };
Build new array of objects with array containing unique data from array of objects with duplicate values of specific key

Build new array of objects with array containing unique data from array of objects with duplicate values of specific key


By : 7obsidian
Date : March 29 2020, 07:55 AM
To fix the issue you can do I need your help... I got an Array of Objects looking something like this: , Lodash answer:
code :
function remap(arr) {
  var out = _.reduce(arr, function(p, c) {
    var key = [c.user, c.title].join('|');
    p[key] = p[key] || { title: c.title, user: c.user, events: [] };
    p[key].events.push({ price: c.price, location: c.location });
    return p;
  }, {});
  return _.map(_.keys(out), function(el) {
    return out[el];
  });
}

remap(arr);
Compare an array of objects in javascript recursively

Compare an array of objects in javascript recursively


By : zoe carlton
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can use Array.prototype.every() and compare all objects in the array using the first object as reference for the comparison.
code :
function compareArray(array) {
  return array.every(compareObjects.bind(null, array[0]));
}
function compareObjects(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

function compareArray(array) {
  return array.every(compareObjects.bind(null, array[0]));
}

var array1 = [ { a: 1 }, { a: 1 }, { a: 1 }, { a: 1 } ];
var array2 = [ { a: 1 }, { b: 1 }, { c: 1 }, { d: 1 } ];

console.log(compareArray(array1));
console.log(compareArray(array2));
How to compare values in an array, that is inside an array of objects, with a property of the objects?

How to compare values in an array, that is inside an array of objects, with a property of the objects?


By : toomek308
Date : March 29 2020, 07:55 AM
should help you out You could take a Map as reference to the nodes and update next by filtering the children with a depth check.
code :
var nodes = [{ id: 37, depth: 0, children: [210, 395, 265], next: [] }, { id: 210, depth: 1, children: [37, 260, 259, 391], next: [] }, { id: 256, depth: 2, children: [265], next: [] }, { id: 259, depth: 2, children: [210, 397, 396], next: [] }, { id: 260, depth: 2, children: [210], next: [] }, { id: 265, depth: 1, children: [37, 256, 388, 394, 271, 269], next: [] }, { id: 269, depth: 2, children: [265], next: [] }, { id: 271, depth: 2, children: [265], next: [] }, { id: 388, depth: 2, children: [265], next: [] }, { id: 391, depth: 2, children: [210], next: [] }, { id: 394, depth: 2, children: [265], next: [] }, { id: 395, depth: 1, children: [37], next: [] }, { id: 396, depth: 3, children: [259, 413], next: [] }, { id: 397, depth: 3, children: [259], next: [] }, { id: 413, depth: 4, children: [396], next: [] }],
    references = new Map(nodes.map(n => [n.id, n]));

nodes.forEach(node => node.next = node.children.filter(
    id => references.get(id).depth > node.depth
));

console.log(nodes);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Posts Related Posts :
  • Chrome-Extension/JavaScript How to make all links on page have no effect?
  • Websocket issue Internet Explorer
  • sessionStorage value becomes null in other tab in AngularJS
  • Split URL from position x to the end in Javascript
  • How to set value of input field with NgIf in Angular 4
  • invalidStateError for second time screenshare on Chrome
  • How do you pass a value to the variable in a xhr.setRequestHeader?
  • I cant start nodemon on my windows 10
  • Nested if else jumps out from the main if else in javascript
  • Iterate through all collections and remove them
  • ES6 - Value of a variable in template string does not increment
  • how to get content of html table cell using javascript javascript depending on checkbox
  • Node.js Working with Multiple Tier SQL
  • Can't allow Cross-Origin Request in local Nodejs server
  • Datatables orderable=false directly on table
  • Dynamically load js content with iron router in meteor using array in return statement
  • Limit checkbox to 2, but moving the select instead of blocking it
  • Why itsn't displaying marker on map?
  • jQuery target next of the same class in the whole DOM
  • encoding must be a valid encoding error in process encoding
  • How to do a date range to view data from selected date highcharts
  • How do I refactor this composed function with Ramda.js?
  • jQuery to serialize selected option's value, not label
  • Convert object to Chartis.js structure
  • Dynamic import with not bundled file
  • Click handler not firing for elements rendered in Ajax Callback - only in Safari
  • Math.max.apply gives an error CreateListFromArrayLike called on non-object
  • get the parent nodes to a given node in d3 dendogram
  • is-dropdown-submenu-parent makes links unclickable on Opera and Chrome
  • JS: Sum column values and updating result on change
  • Query against nested object keys
  • Fullcalendar getting its parent colspan
  • How to retrieve a dynamic number of elements by id
  • How to access redux variables and functions from deep components
  • Efficiently access Array.prorotype.filter single-item returns
  • PHP var into Javascript
  • How to parse json with javascript/jquery if content matches string
  • How can I make a pyramid based on alphabet?
  • Javascript sorting a csv rows and displaying in table
  • How to get specific data from json from api using ajax. The json looks strange to me
  • react js html5 video not working
  • Javascript Angular 4 Change ngClass from another Component
  • Hide multiple table columns with javascript
  • Convert datetime to ISO Format using moment js
  • Dynamically adjust canvas size depending on content
  • setTimeout function with document on click
  • Need advice on nested Promises.all
  • Google Captcha expiration time
  • Syntax of Javascript TAPE unit test
  • Parse php json to javascript
  • Write to Internet Explorer javascript console with vba in excel
  • 2 Forms with Jquery
  • Why the loop stops right in the middle?
  • filter system for restaurant booking
  • how to add active class in framework nav menu when (add/edit) pages are opened
  • Port a js map in dart
  • How to get value from select using javascript
  • Audio won't be muted with JavaScript - removing audio tags with mutationobserver needed
  • How to include an HTML/Javascript game into reactJS website
  • Convert Nodejs server into node module
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org