【问题标题】:Change the value of the key in custom array更改自定义数组中键的值
【发布时间】:2014-08-07 16:08:56
【问题描述】:

单击字段名称的 ASC 或 DESC 链接并创建键:值对对象并将其推送到数组; 如果键存在,则将值替换为选定的单击事件并更新数组键:值;

例子

单击按名称排序 - DESC:

[{"name":"desc"}]

再次单击按名称排序 - ASC:

[{"name":"asc"}]

点击按年龄排序 - DESC:

[{"name":"asc"},{"age":"desc"}]

再次单击按名称排序 - DESC:

[{"name":"desc"},{"age":"desc"} ]

DEMO LINK

$scope.clickME = function(fieldName, orderType) {

    var obj = {};
    obj[fieldName] = orderType;

    updateArray($scope.sortList, obj);

  }

 var updateArray = function(array, newObject) {
  //console.log(newObject);
  var hash = {};
  var i = 0;
    for (i = 0; i < array.length; i++) {
        hash = array[i];
        console.log(array[i]);
        console.log(hash.hasOwnProperty(newObject));
        //How to check the key is same? not the value as am passing same key but value are different
        if (!hash.hasOwnProperty(newObject)) {

        //check for the value and replace it 
        //    object[fieldName] = (newObject[fieldName] === 'asc') ? 'desc' : 'asc';
        //    return;
        }
    }
    array.push(newObject);
};

【问题讨论】:

  • 这里有什么问题?
  • 在数组中查找自定义字段名(姓名、年龄或性别)并将其值替换为“asc”或“desc”;
  • 什么数组?您发布的代码中没有数组。代码应发布在本网站上,而不是从其他地方链接。
  • @Pointy :分享了实际功能所在的演示链接!

标签: javascript jquery underscore.js arrays


【解决方案1】:

您可以使用 jquery 扩展方法。它需要两个对象并将新对象添加到原始对象并替换原始对象。

$scope.clickMe = function(fieldName, orderType)
{
    var obj = {};
    obj[fieldName] = orderType;
    $.extend($scope.sortList, obj);
}

由于您已经将它们都转换为一个对象,因此您只需直接使用 extend。

如果您想使用字符串而不进行强制转换,您可以这样做。

$scope.sortList[fieldName] = orderType;

如果存在则替换该值,如果不存在则添加一个新值

【讨论】:

  • Key 是作为参数传递的字段名,点击事件可以是 ASC 或 DESC;例如:按名称排序:asc desc
  • 更改为显示如何将其与值一起使用,以及如何避免强制转换,因为它始终是单个键值对
猜你喜欢
  • 2020-02-04
  • 2016-09-27
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
相关资源
最近更新 更多