简体   繁体   中英

Compare array against object keys and maintain order

I need to get data of each key from a passed in input array. Let's say my input array is:

Input array: ['我','很','好'] (I very good)

And I have an object with matching keys for each of those, which all have more associated data.

I want to get that data back in the same order.

Unfortunately, the input data order may not always match the order the keys appear in the object, yet I need to maintain the order when I return the resulting key data.

Basically, how can I loop through an array (let's say input array ) and compare against an object and return data against those matching keys in the same order?

Object:

var myObj = {
   "Foo": 
   {
       'wo' :  ['I/me','我'],
       'hao'   : ['good','好'],
   },
   "Bar": 
   {
       'xi': ['wash', '洗'],
       'hen'   : ['very', '很']
   },
   ...
}

Get function:

getValues : function (inputArray) {
        var result = [];
        for (obj in myObj) {
            for (key in myObj[obj]) {
                for (var i = 0; i < inputArray.length; i++) {
                    //IE: if 我 === 我 
                    if (inputArray[i] === myObj[obj][key][1]) {
                        result.push(key);
                        if (result.length >= inputArray.length) {
                            return result;
                        }
                        ...

Result : ['wo', 'hao', 'hen'] (equivalent to 'I, good, very')

But result needs to be: ['wo', 'hen', 'hao'] (equivalent to 'I, very, good')

Note : I am using jQuery if that is of any help.


EDIT: What I could do is split the string initially, then loop through the length of the inputArray and call the getValues one by one.

The issue with this is, now I'm starting over looping through the myObj datastructure with each call, instead of calling once with a string of values and looping through the myObj once, adding each key as it scans down the list.

            var split = inputArray.split('');
            var resultsList = [];

            for (var i = 0; i < split.length; i++) {
                resultsList.push(getValues(split[i]));
            }


getValues : function (word) {

    for (obj in myObj) {
        for (key in myObj[obj]) {
            if (character === myObj[obj][key][0]) {
                return key;
            }
        }
    }
    return 'not found';
},

This solution doesn't feel ideal.

The problem is that you are searching through each key in the object instead of each position in inputArray :

for (obj in myObj) {
    for (key in myObj[obj]) {
        for (var i = 0; i < inputArray.length; i++) {

should be:

for (var i = 0; i < inputArray.length; i++) {
    for (obj in myObj) {
        for (key in myObj[obj]) {

This way will ensure that it will find and add the order that they are inputted instead of in order they are in the object.

 var myObj = { "Foo": { 'wo' : ['I/me','我'], 'hao' : ['good','好'], }, "Bar": { 'xi': ['wash', '洗'], 'hen' : ['very', '很'] }, }; function getValues (inputArray) { var result = []; for (var i = 0; i < inputArray.length; i++) { for (obj in myObj) { for (key in myObj[obj]) { if (inputArray[i] === myObj[obj][key][1]) { result.push(key); //stop loops if results list matches input list if (result.length >= inputArray.length) { return result; } } } } } } var inputResult = getValues(['我','很','好']) , result = ''; for(var index = 0; index < inputResult.length; index ++){ result += inputResult[index] + ' '; } document.write(result);

Try using $.each() , $.inArray()

 var arr = ['我', '很', '好'] , myObj = { "Foo": { 'wo': ['I/me', '我'], 'hao': ['good', '好'], }, "Bar": { 'xi': ['wash', '洗'], 'hen': ['very', '很'] } } , res = []; $.each(myObj, function(index, value) { $.each(value, function(key, val) { if ($.inArray(val[1], arr) !== -1) { // set `key` at `$.inArray(val[1], arr)` index within `res` array res[$.inArray(val[1], arr)] = key } }) }); console.log(res); $("body").html(res.toString())
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>

Unless I am misunderstanding the question, you can use inputArray[i] to do the lookup in myObj[obj] and get the result you are looking for:

var result = [];
for (obj in myObj) {
    for (var i = 0; i < inputArray.length; i++) {
        var value = myObj[obj][inputArray[i]]
        if ($.isArray(value)) {
            result.push(value[0]);
            //stop loops if results list matches input list
            if (result.length >= inputArray.length) {
                return result;
            }

You should iterate over each key of your object (myObj) when searching for each input value:

    function getValues(inputArray) {
       var result = [];
       var arrayLength = inputArray.length;
       for (var i = 0; i < arrayLength; i++) {
          console.log('Searching for ' + inputArray[i]);
          for (var key in myObj) {
             if(inputArray[i] in myObj[key]) {
                result.push(myObj[key][inputArray[i]][0]);
             }
          }
       }

      console.log(result);
      return result;
   }

How about this. Check the Fiddle

var arr = ['我','很','好'];

var myObj = {
   "Foo": 
   {
       'wo' :  ['I/me','我'],
       'hao'   : ['good','好'],
   },
   "Bar": 
   {
       'xi': ['wash', '洗'],
       'hen'   : ['very', '很']
   }
}

function getKey(character) 
{
    for(obj in myObj)
    {
        var objVal = myObj[obj];
        for(innerobj in objVal)
        {
            var innerobjVal = objVal[innerobj];
            if($.inArray(character, innerobjVal) !== -1)
            {
               return innerobj;
            }
        }
    }
}

var resultArr = arr.map(getKey);

console.log(resultArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM