gpt4 book ai didi

javascript - 如何在键 2 等于值 2 的情况下获取键 1 的值? AngularJS

转载 作者:行者123 更新时间:2023-11-27 23:24:30 24 4
gpt4 key购买 nike

我有这个数组对象:

color =[{"id":"1", "name":"black"},{"id":"2", "name":"white"}]

我有一个值 1 来自 $scope.object.id = 1

所以我试图获取颜色名称,其中颜色 id = $scope.object.id。我该怎么做?

我的 html 中有此代码:

<select ng-model="color" ng-options="color.name for color in colorList" class='material-options'></select> 

如何使用该值作为默认选择选项?

最佳答案

您可以只使用filter方法。

var clr = color.filter(function(item){ return item.id === $scope.object.id; });

然后您可以读取name值,如下所示:

var name = clr.length === 1 ? clr[0].name : '';

根据MDN

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

遗憾的是,这就是我们对 clr长度进行额外检查的原因。根据您的上下文,应该只有一种颜色具有此 id 或没有。因此,filter 将创建并返回的数组的长度为 0 或 1。

关于javascript - 如何在键 2 等于值 2 的情况下获取键 1 的值? AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com