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 and return the JSON structure with only matched items
function matchItemsByPath(json1, json2) {
if (!json1 || Object.keys(json1).length === 0) {
console.log("json1 is null or empty");
return null;
}
var results, path1;
if (json1.d && json1.d.results) {
results = json1.d.results;
path1 = 'Id'; // Assuming we are matching on Id in the results array
} else if (json1.value) {
results = json1.value;
path1 = 'id'; // Assuming we are matching on id in the value array
} else {
throw new Error("Unknown JSON structure for json1");
}
var path2 = 'itemId'; // Assuming we are matching on itemId in json2
var itemToMatch = getValueByPath(json2, path2);
var matchedItems = results.filter(function(item) {
var value1 = getValueByPath(item, path1);
return value1 && value1.toString() === itemToMatch.toString();
});
// 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": {
...