简体   繁体   English

将数组与对象键进行比较并保持顺序

[英]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) Input array: ['我','很','好'] (我很好)

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?基本上,我如何遍历数组(假设input array )并与对象进行比较并以相同的顺序针对那些匹配的键返回数据?

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')结果['wo', 'hao', 'hen'] (相当于'我,好,非常')

But result needs to be: ['wo', 'hen', 'hao'] (equivalent to 'I, very, good')但结果必须是: ['wo', 'hen', 'hao'] (相当于'I,very, good')

Note : I am using jQuery if that is of any help.注意:如果有任何帮助,我正在使用 jQuery。


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.编辑:我可以做的是最初拆分字符串,然后遍历 inputArray 的长度并一一调用getValues

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.问题是,现在我开始在每次调用时循环遍历myObj结构,而不是用一myObj调用一次并循环遍历myObj一次,在它向下扫描列表时添加每个键。

            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 :问题是您正在搜索对象中的每个键而不是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()尝试使用$.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:除非我误解了这个问题,否则您可以使用 inputArray[i] 在 myObj[obj] 中进行查找并获得您正在寻找的结果:

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:搜索每个输入值时,您应该遍历对象 (myObj) 的每个键:

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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