[英]Can not iterate through Javascript Object
我有以下object(失眠歸來)
[
{
"field": 10.5,
"this_is_a_bool": 1,
"name": "",
"data": "2018-05-22T03:00:00.000Z",
"field2": null
},
{
"field": 5.3,
"this_is_a_bool": 0,
"name": "Slim Shady",
"data": "2020-01-22T04:45:00.000Z",
"field2": null
}
]
問題是我不能迭代那些“值集”,所以我可以編輯它們。
做這樣的事情:
for (const val in myObj) {
if (val.field2 === null) {
val.field1 = 'flag - ' + val.field1
}
}
我試過的:
for (const val in myObj)
for (const val of myObj)
const [key,value] of Object.entries(myObj)
錯誤:有時它說myObj is not iterable
,有時代碼被忽略。
你為什么不使用簡單的.map()
:
const src = [{"field":10.5,"this_is_a_bool":1,"name":"","data":"2018-05-22T03:00:00.000Z","field2":null},{"field":5.3,"this_is_a_bool":0,"name":"Slim Shady","data":"2020-01-22T04:45:00.000Z","field2":null}], result = src.map(({field, field2, ...rest}) => ({ field: field2 === null? `flag-${field}`: field, field2, ...rest })) console.log(result)
.as-console-wrapper{min-height:100%;}
或...如果您仍想使用 for 循環...(在您的示例中 val 是關鍵)
var myObj = [ { "field": 10.5, "this_is_a_bool": 1, "name": "", "data": "2018-05-22T03:00:00.000Z", "field2": null }, { "field": 5.3, "this_is_a_bool": 0, "name": "Slim Shady", "data": "2020-01-22T04:45:00.000Z", "field2": null } ]; for (const val in myObj) { if (myObj[val].field2 === null){ myObj[val].field = 'flag - ' + myObj[val].field; } } console.log(myObj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.