Home > Software design >  Javascript Function - Parameter match of Object in Array within an Object Loop
Javascript Function - Parameter match of Object in Array within an Object Loop

Time:02-13

var dset2 = {
"DataFile": [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]}

var catValueArray = [];
var vertValueArray = [];
var indValueArray = [];
for (i = 0; i < dset2.DataFile.length; i  ) {
    if (!catValueArray.includes(dset2.DataFile[i].Cat)) {
        catValueArray.push(dset2.DataFile[i].Cat);
    }
    if (!vertValueArray.includes(dset2.DataFile[i].Vert)) {
        vertValueArray.push(dset2.DataFile[i].Vert);
    }
    if (!indValueArray.includes(dset2.DataFile[i].Ind)) {
        indValueArray.push(dset2.DataFile[i].Ind);
    }
    console.log(catValueArray);
    console.log(vertValueArray);
    console.log(indValueArray);
}

Results are

Array [ "D School", "T School", "S School" ];
Array [ "D Safety" ];
Array [ "A Ind", "B Ind" ];

I would like to convert this into a reusable function. IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i  ) {
        if (!array.includes(dataset[i].prop)) {
            array.push(dataset[i].prop);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');

That doesn't work. However, if I move "Cat" inside the function, I can get a result. IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;
function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i  ) {
        if (!array.includes(dataset[i].Cat)) {
            array.push(dataset[i].Cat);
        }
    }
    console.log(array);
}
pullUniqueValues(dsetSwitch, catValueArray);

The end result is to reuse on a a datasets that has over 10 keys that will be used as identifiers and the number of items ill need to access them is very large. Currently because I can not get the Object parameter passed into the function, I have been forced to hard code every instance where I need to access the key. IE: Anytime I need to access "Cat" key, from the Object in the Array DataFile from within the Object dset2, I have to explicerly write the loop with dset2.DataFile[i].Cat.

Additional attempts with no success passing the property parameter into the function.

var DataFile = [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]


var uniqueValues = [];
function giveUniqueValues1(prop){
uniqueValues = DataFile.map(item => item.prop)
  .filter((value, index, self) => self.indexOf(value) === index);
}
function giveUniqueValues2(prop){
uniqueValues = [...new Set(DataFile.map(item => item.prop))];
}

uniqueValues = DataFile.map(item => item.Cat)
  .filter((value, index, self) => self.indexOf(value) === index); // Successs
giveUniqueValues1(Cat); //Failed Error
giveUniqueValues1('Cat'); //Failed Undefined result for uniqueValues;


uniqueValues = [...new Set(DataFile.map(item => item.Cat))]; //Success
giveUniqueValues2('Cat'); //Fail No Values Returned
giveUniqueValues2(Cat); //Fail Error Out

CodePudding user response:

I've made a function that does what you want it to do and only takes an array as an argument.

const array = [
    {
        ID: 1,
        Cat: 'D School',
        Vert: 'D Safety',
        Ind: 'A Ind',
    },
    {
        ID: 2,
        Cat: 'T School',
        Vert: 'D Safety',
        Ind: 'B Ind',
    },
    {
        ID: 3,
        Cat: 'S School',
        Vert: 'D Safety',
        Ind: 'B Ind',
    },
];

const returnUniqueArrays = (arr) => {
    // Create a map to keep track of our arrays
    const arrayMap = {};

    // Iterate for every object in the dataset
    arr.forEach((obj) => {
        for (const [key, value] of Object.entries(obj)) {
            // If an array with that key doesn't already exist, add it and push the value
            if (!arrayMap[key]) {
                arrayMap[key] = [value];
            } else {
                // If the existing array doesn't have the unique value, push it
                arrayMap[key] = [...new Set([...arrayMap[key], value])];
            }
        }
    });

    return Object.values(arrayMap);
};

console.log(returnUniqueArrays(array));

CodePudding user response:

You're almost there! Just change .prop to [prop], so the section in the if would be:

    if (!array.includes(dataset[i][prop])) {
        array.push(dataset[i][prop]);
    }

DEMO

var dset2 = {
    "DataFile": [{
            "ID": 1,
            "Cat": "D School",
            "Vert": "D Safety",
            "Ind": "A Ind",
        },
        {
            "ID": 2,
            "Cat": "T School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        },
        {
            "ID": 3,
            "Cat": "S School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        }
    ]
};

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i  ) {
        if (!array.includes(dataset[i][prop])) {
            array.push(dataset[i][prop]);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');

  • Related