Hemanth Paluri
Hemanth Paluri

Reputation: 363

how to re position the key of an object in a JSON using jquery or javascript

I have two objects which I need to compare. However there is a problem in the position of the keys in an object.

var obj1 = [{
    Name : abc;
    age : 23;
}, {
    Name : def;
    age : 222;
}]

var obj2 = [{
    age : 23;
    Name: abc;
}, {
    age : 222;
    Name : def;
}]

I have tried using the below, but it failed.

(JSON.stringify(obj1) == JSON.stringify(obj2))

Is there a way to swap the position of the keys in an object which iterates throughout the object? I am expecting something like this

var obj1 = [{
    Name : abc;
    age : 23;
}, {
    Name : def;
    age : 222;
}]

var obj2 = [{
    Name : abc;
    age : 23;
}, {
    Name : def;
    age : 222;
}]

Upvotes: 0

Views: 166

Answers (5)

Shubham Gautam
Shubham Gautam

Reputation: 359

well there is better way though examples above will work but they will fail for unknown keys.

function compareArrayObjects(ob1, ob2) {
  let ob1Keys = Object.keys(ob1);
  let ob2Keys = Object.keys(ob2);
  return (ob1Keys.length == ob2Keys.length?(ob1Keys.every(key)=>(obj1[key]==ob2[key]))
   :false); 

}

or 1 line solution will be

_.intersection(obj1,obj2);

Upvotes: 0

Lapinski
Lapinski

Reputation: 11

The keys of an object (unordered) is different from the index of an array (ordered). To compare two arrays of objects and see if they have the same object (with the same key/value pairs) in each of the array elements, you can try this:

function compareArrayOfObjects(array1, array2) {
  return array1.reduce(function(bool, obj, index) {
    return bool && array2[index] && isEqual(obj, array2[index]);
  }, array1.length === array2.length);
}

If you simply need to compare values as simple as numbers and strings, you can implement isEqual() as follows:

function isEqual(a, b) {
  var aKeys = Object.getOwnPropertyNames(a);
  var bKeys = Object.getOwnPropertyNames(b);

  return aKeys.reduce(function(bool, aKey) {
    return bool && (a[aKey] === b[aKey]);
  }, aKeys.length === bKeys.length);
}

If you need deep object comparisons then you probably want a LoDash implementation of _.isEqual().

To put it all together, you will have

    var obj1 = [{
      Name: 'abc',
      age: 23
    }, {
      Name: 'def',
      age: 222
    }];

    var obj2 = [{
      age: 23,
      Name: 'abc'
    }, {
      age: 222,
      Name: 'def'
    }];
    var obj3 = [{}, {}];
    
    function compareArrayOfObjects(array1, array2) {
      return array1.reduce(function(bool, obj, index) {
        return bool && array2[index] && isEqual(obj, array2[index]);
      }, array1.length === array2.length);
    }

    function isEqual(a, b) {
      var aKeys = Object.getOwnPropertyNames(a);
      var bKeys = Object.getOwnPropertyNames(b);

      return aKeys.reduce(function(bool, aKey) {
        return bool && (a[aKey] === b[aKey]);
      }, aKeys.length === bKeys.length);
    }
    console.log('obj1 and obj2 is the same (expected true): ' + compareArrayOfObjects(obj1, obj2));
    console.log('obj1 and obj3 is the same (expected false): ' + compareArrayOfObjects(obj1, obj3));

Upvotes: 1

Thomas
Thomas

Reputation: 12657

Well, as all the other answer already tell you, you'll have to compare the keys, not the objects themselves. Just adding another implementation

function isObject(value) {
  return typeof value === "object" && value !== null;
}

function isSimilar(a, b) {
  if (a === b) return true;
  return isObject(a) && isObject(b) &&
    Object.keys(a).every(key => a[key] === undefined || key in b && isSimilar(a[key], b[key])) &&
    Object.keys(b).every(key => b[key] === undefined || key in a);
}


var obj1 = [{
  Name: 'abc',
  age: 23,
  thisKeyIsIgnoredSinceItIsUndefined: undefined
}, {
  Name: 'def',
  age: 222
}];

var obj2 = [{
  age: 23,
  Name: 'abc'
}, {
  age: 222,
  Name: 'def'
}];

console.log(isSimilar(obj1, obj2))

Upvotes: 0

Weedoze
Weedoze

Reputation: 13953

As @RoryMcCrossan said -

The order of the keys in an object is not guaranteed

You should use this code instead

var obj1 = [{
  Name: 'abc',
  age: 23
}, {
  Name: 'def',
  age: 222
}];

var obj2 = [{
  age: 23,
  Name: 'abc'
}, {
  age: 222,
  Name: 'def'
}];

function isEqual(objA, objB) {
  if (objA.length !== objB.length)
    return false;
  let isequal = true;
  for (let i = 0; i < objA.length; i++) {
    if (objA[i].Name !== objB[i].Name || objA[i].age !== objB[i].age)
      isequal = false;
  }
  return isequal;
}

if(isEqual(obj1, obj2)){
  console.log("Equal");
}else{
  console.log("Not equal");
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337656

The order of the keys in an object is not guaranteed, so any attempt to rearrange them would be redundant.

However given your description, this seems to be an XY problem, as your goal is to compare the objects. The issue you have is that objects cannot be directly compared. Instead, compare their properties, eg.

if (obj1[i].Name == obj2[i].Name && obj1[i].age == obj2[i].age) {
  // do something...
}

Upvotes: 0

Related Questions