gpt4 book ai didi

javascript - 更改自定义数组中键的值

转载 作者:行者123 更新时间:2023-12-03 12:06:02 25 4
gpt4 key购买 nike

单击字段名的 ASC 或 DESC 链接,创建一个键:值对对象并将其推送到数组中;如果键存在,则用选择的点击事件替换该值并更新数组 key:value;

示例

单击按名称排序 - 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);
};

最佳答案

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

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

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

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

$scope.sortList[fieldName] = orderType;

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

关于javascript - 更改自定义数组中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187267/

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