[英]Javascript-searching for a string in the properties of an array of objects
[英]Javascript Searching Array for partial string
有一個返回對象數組的函數。 該數組具有一個帶有名稱字段的rate對象。 名稱字段內是諸如“慢速”和“最快”的名稱。
我寫了以下內容,希望創建一個新的數組,該數組將過濾掉數組的值,只返回那些與rate [i] .name匹配的“ Slow”值。
到目前為止,我在開發人員控制台中遇到此錯誤。 “未捕獲的TypeError:value.substring不是函數”
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
//value = rates[index];
if (value.substring(0, 5) === "Stand") {
result = value;
newArr.push();
break;
}
}
在控制台中返回數組的一部分。
"rates":[{"id":1123,"price":"1.99","name":"Slow speed - Red Car","policy":{"durqty":1,"durtype":"D","spdup":15000,"spddwn":15000}
您在每個數組位置都有一個對象,而不是字符串本身,請嘗試以下操作:
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
name = rates[index].name;
if (name.substring(0, 4) === "Slow") {
newArr.push(rates[index]);
}
}
嘗試使用filter
功能,這樣看起來更干凈
var newArr = rates.filter(function(rate){
return rate.name && rate.name.substring(0,4) === "Slow";
});
您可以使用filter
執行此操作,例如:
var newArr = rates.filter(function(val){
// check if this object has a property `name` and this property's value starts with `Slow`.
return val.name && val.name.indexOf("Slow") == 0;
});
如@ 4castle所述,可以使用也許更有效的slice(...)
代替indexOf(...)
,例如: val.name.slice(0,4) == "Slow"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.