我有以下内容:
对象的样本集合
var myObjects = [
{ name: "Object1", shape: "circle", color: "red" },
{ name: "Object2", shape: "square", color: "orange" },
{ name: "Object3", shape: "triangle", color: "yellow" },
{ name: "Object4", shape: "circle", color: "green" },
{ name: "Object5", shape: "sphere", color: "blue" },
{ name: "Object6", shape: "hexagon", color: "indigo" },
{ name: "Object7", shape: "square", color: "violet" }
];
我得到一个只有符合特定条件的对象的数组。返回一个只有红色对象的数组
var myRedObjects = $filter('filter')(myObjects, { color: "red" });
现在我的问题是我如何更新数组myObjects中的过滤器对象名称。
答案 0 :(得分:0)
将过滤器使用情况更改为:
var myRedObjects = $filter('filter')(myObjects, { color: "red" }).map(function(currentObject){
currentObject.name = "myNewName",
}
map
将迭代过滤后的数组(非常类似于foreach),并允许您更改当前迭代对象的名称。
请注意map
它与IE< = 9中的所有浏览器兼容。如果您要定位旧浏览器,则需要添加polyfill或不使用map at all(一个简单的for
将完成工作)。
您可以在地图函数here上找到更多信息。
答案 1 :(得分:0)
试试这个
extension String {
var lastThreeLettersAreNumbers: Bool {
if case let chars = characters.suffix(3), chars.count > 2 {
return chars.flatMap{Int(String($0))}.count == 3
}
return false
}
}
/* example usage, common for both Swift 2.2/3 version */
let str1 = "SACH092"
let str2 = "SACH0B2"
print(str1.lastThreeLettersAreNumbers) // true
print(str2.lastThreeLettersAreNumbers) // false
答案 2 :(得分:0)
$ filter 通过引用为您提供过滤后的元素,因此您可以更新 $ filter(' filter')的成员(myObjects,{color:&#直接34;红色"}),它会在 myObjects 变量中进行更改。
请尝试以下代码:
var myRedObjects = $filter('filter')(myObjects, { color: "red" });
for (var index in myRedObjects) {
myRedObjects[index].name = 'newName';
}
或者,如果您使用的是 underscore.js ,那么:
_.each(
$filter('filter')(myObjects, { color: "red" }),
function(item){
item.name = 'newName';
}
);
答案 3 :(得分:0)
var myObjects = [
{ name: "Object1", shape: "circle", color: "red" },
{ name: "Object2", shape: "square", color: "orange" },
{ name: "Object3", shape: "triangle", color: "yellow" },
{ name: "Object4", shape: "circle", color: "green" },
{ name: "Object5", shape: "sphere", color: "blue" },
{ name: "Object6", shape: "hexagon", color: "indigo" },
{ name: "Object7", shape: "square", color: "violet" }
];
var myRedObjects = $filter('filter')(myObjects, { color: "red" });
// filter returns Array so
myRedObjects.forEach(function(Obj) {
var idx = myObjects.indexOf(obj);
myObjects[idx].name = "Update name";
});
答案 4 :(得分:0)
Luxor001答案是对的。这是我需要和工作不错基本上我想改变原始值的名称而不是过滤器数组值,并借助Map它的工作很酷。
var myRedObjects = $filter('filter')(myObjects, { color: "red" }).map(function(currentObject){
currentObject.name = "myNewName",
}