简体   繁体   English

遍历对象属性

[英]Iterate over object properties

In my aurelia app, I need to display a list of elements. 在我的aurelia应用程序中,我需要显示一个元素列表。 For performance reasons, these elements are stored as a javascript object instead of an array. 出于性能原因,这些元素存储为javascript对象而不是数组。 That is what the object looks like : 那就是对象的样子:

var x = {
    0 : {...},
    3 : {...},
    5 : {...},
}

Here is the part of the template where I display these elements : 这是模板中显示这些元素的部分:

<template>
    <ul>
        <li repeat.for="property of object | ObjectToArray">
            ${ property.text }
        </li>
    </ul>
</template>

As you can see, I'm currently using a value converter to be able to iterate over my object properties. 如您所见,我当前正在使用一个值转换器来迭代我的对象属性。 The value converter simply converts the object to an array : 值转换器将对象简单地转换为数组:

export class ObjectToArrayValueConverter {
    toView(data : {[key : string] : any}) : any[] {

        var array = [];

        for (var key in data) {
            array.push(data[key]);
        }

        return array;
    }
}

This solution works very well as long as properties do not get removed or added to the object after the list has been rendered for the first time. 只要在第一次呈现列表后不会将属性删除或添加到对象,该解决方案就可以很好地工作。 The reason is that the value converter only gets called once. 原因是值转换器仅被调用一次。 In my case, however, I need my list to stay up to date whatever happens. 但是,就我而言,无论发生什么情况,我都需要我的清单以保持最新。

I know I could create a function that could be manually called every time the object is modified, but that would add some unwanted complexity in business logic. 我知道我可以创建一个可以在每次修改对象时手动调用的函数,但这会增加一些不必要的业务逻辑复杂性。

Is there an aurelia functionality that coud help me achieve what I want ? 是否有aurelia功能可以帮助我实现所需的功能? I could not find any help in the docs. 我在文档中找不到任何帮助。 Thank you ! 谢谢 !

You can get the keys using Object.prototype.keys and call Array.prototype.map on it to get an array every time you want to list it out. 您可以使用Object.prototype.keys来获取键,并在每次要列出它时调用Array.prototype.map以获得一个数组。

var obj={...}; //Object with many keys
var genArray = Object.keys(obj).map(function(key){return obj[key];})


//Using as a function
function getKeysAsArray(obj){
    if(!obj){
        return [];
    }
    return Object.keys(obj).map(function(key){return obj[key]});
}

There's an easier strategy, as shown in the docs : 有一个更简单的策略,如docs所示:

export class KeysValueConverter {
  toView(obj) {
    return Reflect.ownKeys(obj);
  }
}

Usage: 用法:

<p repeat.for="greeting of friends | keys">${greeting}, ${friends[greeting].name}!</p>

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

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