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

12

我有一个对象,我想迭代该对象的一些特定键。如何实现?

考虑下面的片段:

如何迭代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"
};


不要使用for (var key in table_object),而是使用for (var key of ["table1", ...]) - Bergi
{btsdaf} - Karan Dhir
{btsdaf} - Bergi
或许将“tables”和“tablenames”存储为两个单独的数组会更容易些。 - Bergi
{btsdaf} - Jared Smith
我认为这不是制作表格的正确方式。通过制作两个或更多的数组,您可以记录一个表格,并迭代行。 - Samū
7个回答

16

您可以筛选键,然后迭代其余部分。

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


/^table(\d+)$/将明确匹配以table开头,后跟一些数字的字符串。 - Samū
{btsdaf} - kamoroso94
/^([a-zA-Z0-9$]+)$/,或者 /^([a-zA-Z$]+)(\d+)$/。或者您可以更改正则表达式,或整个过滤函数。 - Samū

7

您需要指定要迭代的键:

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


{btsdaf} - Samū

3
你需要使用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);


2
{btsdaf} - Ilmari Karonen
{btsdaf} - Mihai Alexandru-Ionut
{btsdaf} - Bergi

2
你可以尝试像这样做:
var keys = ['table1', 'table2', 'table3']
Object.keys(table_object).forEach(function(key) {
    if (keys.indexOf(key) != -1) {
        var table_value = table_object[key]
    }
})

{btsdaf} - Samū

1

可能无法遍历有限键,但您可以拥有一个键数组,您想要迭代。然后循环该数组以从对象中获取相应的值

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

})


{btsdaf} - Samū

1
我认为在这种情况下更好的做法是将您的对象制作成这样:

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

或者你可以创建两个数组:

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

你可以使用这种方法制作表格。
但无论你的问题是什么:

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" ] );
}

方法2将是最佳选择。


1
你不需要花哨的过滤器或正则表达式来完成如此简单的任务!忽略那些误导性的答案,开始使用JavaScript的全部威力!你应该在对象上使用Object.defineProperty()方法,并将你不想遍历的所有属性设置为enumerable: false。这样做还可以将你的命名约定与你的逻辑解耦。让我展示给你看:

// 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]);
}

不可枚举的属性仍然可以使用Object.getOwnPropertyNames()检索出来,与所有可枚举的属性一起。
但是,如果您计划实际使用这种第二种方法来遍历所有属性,当不再需要过滤时,我必须给您一些建议:
  • enumerable可以设置回true,因此如果只是一次更改,我强烈建议还原它。

  • 如果过滤经常来回切换,则应仔细检查对象的结构,因为可能有更适合您需求的选项(例如将数组放入对象中)。


我考虑过那个方法,但它比筛选键的方法慢得多。 - Samū
另外,如果你真的关心性能,为什么不使用循环而非过滤函数?(https://jsperf.com/array-filter-performance)。当然,我并不是说这是最快的解决方案,但我认为这是最语义化正确的解决方案,最重要的是,它不会太慢以至于让你的浏览器卡死。;P - DoNotDownvote_JustUpvote

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接