JSFiddle - React, Tailwind, and code Playground

by dshilkret

JavaScript

// Function to get the value at a specific JSON path
function getValueByPath(obj, path) {
  return path.split('.').reduce(function(acc, part) {
    // Handle array index
    var match = part.match(/(\w+)\[(\d+)\]/);
    if (match) {
      var arrayProp = match[1];
      var index = parseInt(match[2], 10);
      return acc && acc[arrayProp] && acc[arrayProp][index];
    } else {
      return acc && acc[part];
    }
  }, obj);
}

// Function to match items dynamically using full JSON paths and return the JSON structure with only matched items
function matchItemsByPath(json1, path1, json2, path2) {
  var results;
  if (json1.d && json1.d.results) {
    results = json1.d.results;
  } else if (json1.value) {
    results = json1.value;
  } else {
    throw new Error("Unknown JSON structure for json1");
  }

  var itemToMatch = getValueByPath(json2, path2);
  var matchedItems = [];

  for (var i = 0; i < results.length; i++) {
    var value1 = getValueByPath(results[i], path1.split('.').slice(-1)[0]);
    if (value1.toString() === itemToMatch.toString()) {
      matchedItems.push(results[i]);
    }
  }

  // Return the filtered structure
  if (json1.d && json1.d.results) {
    return { d: { results: matchedItems } };
  } else if (json1.value) {
    return { value: matchedItems };
  }
}

// Sample JSON data
var json1a = {
  "d": {
    "results": [
      {
        "__metadata": {
          "id": "1cf20660-c7bc-4eb4-8f19-c37d87bbdbca",
          "uri": "https://dtecho365.sharepoint.com/sites/ServiceNowDev1/_api/Web/Lists(guid'8ff1da2f-0d77-4507-99da-e7681a013119')/Items(5933)",
          "etag": "\"1\"",
          "type": "SP.Data.Dev1Lib3Item"
        },
        // ... other fields
        "Id": 5933
      },
      {
        "__metadata": {
          "id": "b35cdd46-e985-42da-92a4-49f0cf353f73",
          "uri": "https://dtecho365.sharepoint.com/sites/ServiceNowDev1/_api/Web/Lists(guid'8ff1da2f-0d77-4507-99da-e7681a013119')/Items(5934)",
          "etag": "\"1\"",
       ...