简体   繁体   English

如何在JavaScript中迭代Object的特定键?

[英]How to iterate over an Object's specific keys in JavaScript?

I have an object and I want to iterate over some specific keys of that object. 我有一个对象,我想迭代该对象的一些特定键。 How to achieve this? 怎么做到这一点?

Consider the snippet below: 考虑下面的代码:

How can I iterate over table1,table2 and table3 keys and not all of them? 我如何迭代table1,table2和table3键而不是所有键?

 var table_object = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "Bonjour", table3_name: "greetings_french.html" }; 

You could filter the keys and then iterate the rest. 您可以过滤密钥然后迭代其余部分。

 var table_object = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "Bonjour", table3_name: "greetings_french.html" }; Object .keys(table_object) .filter(function (k) { return !/_/.test(k); }) .forEach(function (k) { console.log(table_object[k]); }); 

You have to specify which keys you have to iterate through: 您必须指定必须迭代的键:

 var table_object = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "Bonjour", table3_name: "greetings_french.html" }; var keysToIterateThrough = ["table1", "table2", "table3"]; keysToIterateThrough.forEach(key => { var value = table_object[key]; console.log(`key: ${key} => value: ${value}`); }) 

You have to use Object.keys in order to find out all the object keys then apply a filter method in order to filter them. 您必须使用Object.keys来查找所有对象键,然后应用filter方法以过滤它们。

 var table_object = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "Bonjour", table3_name: "greetings_french.html" }; var keysToIterate = ["table1", "table2", "table3_name"]; let values=Object.keys(table_object) .filter(a=>keysToIterate.includes(a)) .map(a=> table_object[a]); console.log(values); 

Could try something like 可以试试像

var keys = ['table1', 'table2', 'table3']
Object.keys(table_object).forEach(function(key) {
    if (keys.indexOf(key) != -1) {
        var table_value = table_object[key]
    }
})

It may not be possible to iterate over limited keys, but you can have an array of keys which you want to iterate. 可能无法迭代有限的键,但您可以拥有要迭代的键数组。 Then loop over that array to get the corresponding value from the object 然后遍历该数组以从对象获取相应的值

 var objKeys = ['table1', 'table2', 'table3'] var table_object = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "Bonjour", table3_name: "greetings_french.html" }; objKeys.forEach(function(item) { console.log(table_object[item]) }) 

I think a better way to do it in this case is making your object like this: 我认为在这种情况下更好的方法就是让你的对象像这样:

 var table = { "hello world": "greetings_english.html", "hola": "greetings_spanish.html", "bonjour": "greetings_french.html" }; for( var i in table ) { console.log( i ); console.log( table[ i ] ); } 

Or you could create two arrays: 或者你可以创建两个数组:

 var greetings = [ "hello world", "hola", "bonjour" ]; var names = [ "greetings_english.html", "greetings_spanish.html", "greetings_french.html" ]; for( var i = 0; i < greetings.length; i ++ ) { console.log( greetings[ i ] ); console.log( names[ i ] ); } 

You can make a table using this method 您可以使用此方法创建表

But in any case of your question: 但无论如何你的问题:

 var table = { table1: "hello world", table1_name: "greetings_english.html", table2: "hola", table2_name: "greetings_spanish.html", table3: "bonjour", table3_name: "greetings_french.html" }; // Now there are three methods console.log( "--- Method 1 ---" ); Object.keys( table ) .filter( function( key ) { return /^table(\\d+)$/.test( key ); } ) .forEach( function( key ) { console.log( key ); console.log( table[ key ] ); console.log( table[ key + "_name" ] ); } ); console.log( "--- Method 2 ---" ); for ( var i in table ) { if ( /^table(\\d+)$/.test( i ) ) { console.log( i ); console.log( table[ i ] ); console.log( table[ i + "_name" ] ); } } console.log( "--- Method 3 ---" ); var keys = [ "table1", "table2", "table3" ]; for ( var i = 0; i < keys.length; i ++ ) { console.log( keys[ i ] ); console.log( table[ keys[ i ] ] ); console.log( table[ keys[ i ] + "_name" ] ); } 

Method 2 would be the best. 方法2将是最好的。

You don't need fancy filters or regular expression to accomplish such a simple task! 您不需要花哨的过滤器或正则表达式来完成这么简单的任务! Ignore those misleading answers and start using the full power of JavaScript! 忽略那些误导性的答案,并开始使用JavaScript的全部功能!
You should use the Object.defineProperty() method on your object and set to enumerable: false all the properties you don't want to iterate through. 您应该在对象上使用Object.defineProperty()方法并设置为enumerable: false所有您不想迭代的属性。 In this way you also decouple your naming convention from your logic. 通过这种方式,您还可以将命名约定与逻辑分离。 Let me show you: 让我演示给你看:

 // Defining iterable properties. This ones will be returned // by Object.keys() var table_object = { table1: "hello world", table2: "hola", table3: "Bonjour", // It works even if you declare them in advance // table1_name: "greetings_english.html", // table2_name: "greetings_spanish.html", // table3_name: "greetings_french.html", }; // Declaring the not iterable properties. They can still be // accessed, but they will not be iterated through Object.defineProperty(table_object, "table1_name", { // delete the next line if you have already declared it value: "greetings_english.html", enumerable: false }); Object.defineProperty(table_object, "table2_name", { // delete the next line if you have already declared it value: "greetings_spanish.html", enumerable: false }); Object.defineProperty(table_object, "table3_name", { // delete the next line if you have already declared it value: "greetings_french.html", enumerable: false }); // Iterating through the object using for ... in, which iterates // over the keys for (var key in table_object) { console.log(table_object[key]); } 

The not enumerable properties can still be retrieved along with all the enumerable ones using Object.getOwnPropertyNames() . 使用Object.getOwnPropertyNames()仍然可以检索不可枚举的属性以及所有可枚举的属性。
However, if you are planning to actually use this second method to iterate through all the properties when filtering is not needed anymore I've to give you some advice: 但是,如果您计划在不再需要过滤时实际使用第二种方法迭代所有属性,我会给您一些建议:

  • enumerable can be set back to true , so if it a one-time change I'd highly suggest to revert it. enumerable可以设置为true ,所以如果它是一次性更改,我强烈建议将其还原。

  • If filtering is toogled back and forth more often than not, then you should check twice the structure of your object, since there may be more suitable options for your needs (such as arrays into the object). 如果过滤频繁地来回转换,则应该检查对象结构的两倍,因为可能有更合适的选项满足您的需求(例如数组到对象中)。

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

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