【问题标题】:Underscore JS Update array of objects by key value pair下划线 JS 通过键值对更新对象数组
【发布时间】:2016-10-21 05:18:41
【问题描述】:

假设我有一个这样的对象数组:

$scope.colors = [
  {color:'Teal', id:5},
  {color:'Black', id:8},
  {color:'Red', id:9}
];

我想做这样的事情

$scope.colors = _update(color='Yellow' where id=8);

你将如何在 underscorejs 中完成这样的事情?还是 Lodash 或 Typescript 是此类事情的最佳选择?

目标是让新数组如下所示:

$scope.colors = [
  {color:'Teal', id:5},
  {color:'Yellow', id:8},
  {color:'Red', id:9}
];

我来自 PHP / MySQL 背景。

【问题讨论】:

    标签: javascript angularjs underscore.js lodash


    【解决方案1】:

    您可能不需要 underscore.js。 Array.map 会做到的。

    var colors = [
      {color:'Teal', id:5},
      {color:'Black', id:8},
      {color:'Red', id:9}
    ];
    
    colors.map(function(i){
    
        if(i.id == 8) {
            i.color= 'Yellow'; 
        }
        return i;
    
    });
    
    console.log(colors);

    【讨论】:

    • 由于某种原因,此方法在 Angular 中不起作用,我将对象放在范围变量 ($scope.colors) 中,不知道为什么它在 Angular 中不起作用但在常规 javascript 中起作用.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2016-10-31
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多