1

i am trying to find a list of synced users between two arrays (objArray1 & objArray2) and return the data from objArray1 along with 'aid' in Objarray2. I have the below code working, but i am trying to see if can return 'aid' from objArray2 as well in the below format.

Code sample below

// SystemA
    const objArray1 = [
      { id: "1", name: "John" },
      { id: "2", name: "Jack" },
      { id: "3", name: "Sam" },
      { id: "4", name: "Bill" },
    ];

    // SystemB
    const objArray2 = [
      { id: "1", name: "John", aid:"uuud2905555" },
      { id: "3", name: "Sam" }, aid:"uuud29029303"
      { id: "5", name: "Bob" }, aid:"uuud29435454"
    ];

    const array1IDs = objArray1.map((item) => {
      return item.id
    })
    // Result: array1IDs = ["1", "2", "3", "4"];

    const array2IDs = objArray2.map((item) => {
      return item.id
    })
    // Result: array2IDs = ["1", "3", "5"];

    // FIND SYNCED USERS
    // Compare the id value of each item in objArray1 with each item of objArray2
    // Return the ones that match. 
    const syncedUsers = objArray1.filter((item) => {
      const found = objArray2.find((element) => element.id === item.id);
      return found;
    });

Required JSON Format, please note that all matching items should be returned from objArray1, with the exception of 'aid' from objArray2

{
            "records": [
                {
                    "id": {aid},                // from objArray2
                    "fields": {
                        "Name":{name},          // from objArray1  
                        "sid": {id}             // from objArray1
                }
                ]
    }

2 Answers2

1

Presented below is one possible way to achieve the desired objective.

Code Snippet

// method to create result as "JSON"
const createJSON = (arr1, arr2) => (
  // use "stringify" to transform JavaScript object into JSON
  JSON.stringify({
    // set-up the "records" prop
    records: arr2
      .filter(          // filter to keep only those that have matching "id"
        ({ id }) => arr1.some(ob => ob.id === id)
      )
      .map(             // de-structure & rename props to match desired objective
        ({ id : sid, name : Name, aid: id }) => ({
          id,
          fields: {Name, sid}
        })
      )
  })
);

// SystemA
const objArray1 = [
  { id: "1", name: "John" },
  { id: "2", name: "Jack" },
  { id: "3", name: "Sam" },
  { id: "4", name: "Bill" },
];

// SystemB
const objArray2 = [
  { id: "1", name: "John", aid:"uuud2905555" },
  { id: "3", name: "Sam", aid:"uuud29029303" },
  { id: "5", name: "Bob", aid:"uuud29435454" },
];

console.log('result as a JSON: ', createJSON(objArray1, objArray2));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments added to the snippet above.


EDIT Use name and id from array-1. Used restOfArr1Props to account for all other props of array-1 objects to be included.

const createJSON = (arr1, arr2) => (
  JSON.stringify({
    records: arr1
      .filter(
        ({ id }) => arr2.some(ob => ob.id === id)
      )
      .map(
        ({ id : sid, name : Name, ...restOfArr1Props }) => ({
          id: arr2.find(a2 => a2.id === sid)?.aid ?? 'missing aid',
          fields: {
            Name, sid, ...restOfArr1Props
          },
        })
      )
  })
);

// SystemA
const objArray1 = [
  { id: "1", name: "John", prop1: 'value11', prop2: 'value12' },
  { id: "2", name: "Jack", prop1: 'value21', prop2: 'value22' },
  { id: "3", name: "Sam", prop1: 'value31', prop2: 'value32' },
  { id: "4", name: "Bill", prop1: 'value41', prop2: 'value42' },
];

// SystemB
const objArray2 = [
  { id: "1", name: "John", aid:"uuud2905555" },
  { id: "3", name: "Sam", aid:"uuud29029303" },
  { id: "5", name: "Bob", aid:"uuud29435454" },
];

console.log('result as a JSON: ', createJSON(objArray1, objArray2));
.as-console-wrapper { max-height: 100% !important; top: 0 }
jsN00b
  • 3,584
  • 2
  • 8
  • 21
  • Hello thanks, i have one more question, is there a way to simplify this by pushing all the matching properties from array 1 after the fields object ? – Antony Rappai May 04 '22 at 09:52
  • Thanks, jsNoob, however, i had one more question, in my actual array i have more than two items that i want to return, so mapping them can be a pain, is there a simpler way to return the all the items from objArray1 that matches objArray2 but also include the aid from objArray2 for the ones that match. So basically objArray1 is the source of truth – Antony Rappai May 04 '22 at 12:22
  • **EDIT** updated to use `restOfArr1Props`. :-) Have also updated array-1 to reflect additional prop-value pairs. All of these are placed within the `fields` object. If these need to be position outside of `fields`, please clarify. – jsN00b May 04 '22 at 12:43
  • 1
    Hey Mr jsN00b, i think that works, i got nothing but admiration for guys who can play with all sorts of arrays. – Antony Rappai May 04 '22 at 13:12
  • I had no clue of restOfArr1Props – Antony Rappai May 04 '22 at 13:49
  • It is just a variable-name. You may use another name instead - and it'll still work. What is happening is that the object within the `.map()` iterator is being de-structured and it's props are directly-accessed. So, `id` becomes `sid`, and `name` becomes `Name`. Then `...restOf` ensures that all remaining props are part of the variable `restOf`. And, we just use that variable within `fields` object - and voila all props are now inside `fields`. :-) I'm also learning JavaScript and was pleasently-surprised at how elegant it is, when I learned about this. – jsN00b May 04 '22 at 13:53
  • can not find any documentation on restOfArr1Props – Antony Rappai May 04 '22 at 13:55
  • Yeah - because it's just a variable name. You can search for [`destructuring`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and/or `destructuring assignment`. – jsN00b May 04 '22 at 13:56
0
const objArray1 = [
 { id: '1', name: 'John', type: 'bully' },
 { id: '2', name: 'Jack', type: 'sporty' },
 { id: '3', name: 'Sam', type: 'kind' },
 { id: '4', name: 'Bill', type: 'poliet' },
];


const objArray2 = [
{ id: '1', name: 'John', aid: 'uuud2905555' },
{ id: '3', name: 'Sam', aid: 'uuud29029303' },
{ id: '5', name: 'Bob', aid: 'uuud29435454' },
];

const syncedUsers = { records: [] };

 for (let user1 of objArray1) {
  const foundUser = objArray2.find(user2 => user2.id === user1.id);

   if (foundUser) {
    syncedUsers.records.push({
    id: foundUser.aid,
    fields: { sid: user1.id, name: user1.name, ...user1 },
      });
    }
  }

console.log(JSON.stringify(syncedUsers));
  • managed to hack together something by looking at a few other examples, i am having a hard time processing the filter and map, my brain could not handle it, this is a more novice way i think, but i managed to use the ... spread operator as well. – Antony Rappai May 05 '22 at 09:08