Ad

Way To Create A Function Regarding JSON, And Array For Changing The Text Value Of An Element

- 1 answer

I have this example JSON

data = JSON.parse(dataLang);
//which produces this
{
    "Scientific Name1a":"Normal Name1",
    "Scientific Name2a":"Normal Name2",
    "Scientific Name3a":"Normal Name3",
    "Scientific Name4a":"Normal Name4",
}

or
{
    "Locality Names1":"Normal Name1",
    "Local Name2":"Normal Name2",
    "Local Name3":"Normal Name3",
}

Or Depends on the selected value of the user depending whether Scientific or Local Name.

After that I'm confused on how I will implement changing the Name of an element,Context Menu,etc..

Is there any way to implement a function that will process the pass words, for example

Scenario A

CallFunction(["Normal Name1,Normal Name2"]);

function CallFunction(collection){
//How to implement
return ["Scientific Name1a,Scientific Name2a"]
}

Scenario B

CallFunction("Local Name2");

function CallFunction(collection){
return "Normal Name2"
}
Ad

Answer

You should pass an array of separate strings to CallFunction, not a single string.

CallFunction(["Normal Name1", "Normal Name2"]);

Then the function can loop through data and return the keys that have matching values.

function CallFunction(collection) {
    var result = [];
    for (var key in data) {
        if (collection.indexOf(data[key]) != -1) {
            result.push(key);
        }
    }
    return result;
}

This will return an array like [Scientific Name1a", "Scientific Name2a"]. As with the input, each string is a separate array element in the result, not combined into one element; if you want to combine them into a single string, you can use .join() after the function returns.

It would be more efficent if you inverted your data array.

var dataByNormal = {};
for (var scientific in data) {
    dataByNormal[data[scientific]] = scientific;
}

Then CallFunction could be written as:

function CallFunction(collection) {
    var result = [];
    for (var i = 0; i < collection.length; i++) {
        if (collection[i] in dataByNormal) {
            result.push(dataByNormal[collection[i]]);
        }
    }
    return result;
}

If you want CallFunction to be able to take either an array or a single string, it can check the type of the argument first.

function CallFunction(collection) {
    if (typeof collection == "string") {
        // If we're called with a single string, treat it like a 1-element array
        collection = [collection];
    }
    // ...
}
Ad
source: stackoverflow.com
Ad