const data = [{
"id": 1,
"name": "Vinay Kumar",
"username": "vinayk",
"email": "vinayk@abcu.com",
"address": {
"street": "random1",
"suite": "APR",
"city": "Mumbai",
"zipcode": "192008-13874",
"geo": {
"lat": "-17.3159",
"lng": "91.1496"
}
},
"website": "seuinfra.org",
"company": {
"name": "sec infra",
"basename": "seu infra tech"
}
},
{
"id": 2,
"name": "Anandita Basu",
"username": "PrernaB",
"email": "Anandita.b@abc1f.cpm",
"address": {
"street": "Hawroh Bridge",
"suite": "ATY",
"city": "Kolkata",
"zipcode": "700001",
"geo": {
"lat": "-67.3159",
"lng": "91.8006"
}
},
"website": "techInfar.org",
"company": {
"name": "tech infar world",
"basename": "seu infra tech"
}
}
];
function getMatchedIds(inputArr) {
const len = inputArr.length;
if(len !== 3) {
return [-1];
}
const action = inputArr[1];
const paramArr = inputArr[0].split(".");
const dataLen = data.length;
if(action === "EQUALS") {
for(let obj of data) {
const val = getNestedValue(obj, paramArr);
if(val === inputArr[2]) {
return [obj.id];
}
}
return [-1];
}else if(action === "IN") {
const allowedValArr = inputArr[2].split(",");
const allowedValArrLen = allowedValArr.length;
const result = new Array(allowedValArrLen).fill(-1);
for(let obj of data) {
const val = getNestedValue(obj, paramArr);
for(let i=0;i<allowedValArrLen;i++) {
if(result[i] === -1 && allowedValArr[i] === val) {
result[i] = obj.id;
}
}
let allDone = true;
for(let res of result) {
if(res === -1) {
allDone = false;
break;
}
}
if(allDone) {
return result;
}
}
return result;
}
return [-1];
}
function getNestedValue(dataObj, paramArr, index=0) {
if(dataObj === null || dataObj === undefined || typeof dataObj !== "object") {
return "";
}
const len = paramArr.length;
const key = paramArr[index];
const result = dataObj[key];
if(len-1 === index) {
return result;
}else {
return getNestedValue(result, paramArr, index+1);
}
}
console.log(getMatchedIds(["username", "EQUALS", "vinayk"]));
console.log(getMatchedIds(["address.city", "EQUALS", "Kolkata"]));
console.log(getMatchedIds(["address.city", "IN", "Mumbai,Kolkata"]));
console.log(getMatchedIds(["username", "EQUALS", "Tom"]));