更改自定义数组中键的值

时间:2020-12-24 21:31:05

Click on the either ASC or DESC link for fieldname and create an key:value pair object and push it to an array; If key exists replace the value with click event selected and updated the arrays key:value;

单击ASC或DESC链接以获取fieldname并创建一个key:value对象并将其推送到一个数组;如果key存在,则用选择的click事件替换该值并更新数组key:value;

Example

Click Sort By Name - DESC:

单击按名称排序 - DESC:

[{"name":"desc"}]

Again Click Sort By Name - ASC:

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

[{"name":"asc"}]

Click Sort By Age - DESC:

单击按年龄排序 - DESC:

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

Again Click Sort By Name - DESC:

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

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

DEMO LINK

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

1 个解决方案

#1


1  

you can use the jquery extend method. It takes two objects and adds the new to the original and replaces the original.

你可以使用jquery extend方法。它需要两个对象并将新内容添加到原始对象并替换原始对象。

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

Since you are already casting them both to an object, you do just use extend directly.

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

if you want to use the strings and not do the cast you can do this.

如果你想使用字符串而不是演员,你可以这样做。

$scope.sortList[fieldName] = orderType;

it will replace the value if it is there, and add a new one if it isn't

如果存在,它将替换值,如果不存在,则添加新值

#1


1  

you can use the jquery extend method. It takes two objects and adds the new to the original and replaces the original.

你可以使用jquery extend方法。它需要两个对象并将新内容添加到原始对象并替换原始对象。

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

Since you are already casting them both to an object, you do just use extend directly.

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

if you want to use the strings and not do the cast you can do this.

如果你想使用字符串而不是演员,你可以这样做。

$scope.sortList[fieldName] = orderType;

it will replace the value if it is there, and add a new one if it isn't

如果存在,它将替换值,如果不存在,则添加新值