gpt4 book ai didi

javascript - 如何通过对象数组运行 forEach 并为具有空字符串的对象属性设置值?

转载 作者:行者123 更新时间:2023-11-29 18:03:43 25 4
gpt4 key购买 nike

第 1 部分问题:如何使用 forEach 遍历我的对象数组以将具有空字符串的 profile_image_url 的对象属性设置为默认链接/值("/media/artist/img_0930-1-9654.jpg")。仅设置空字符串的值。我现在正在探索 forEach 循环。下面是我的示例 json。我有 20000 个用户的 json。

第 2 部分问题:我更适合哪一个?遍历 forEach 还是常规 for 循环?

JSON

[{
"country": "",
"artist_id": 4,
"email": "LzoCqLeVpy8h@example.com",
"profile_image_url": ""
}, {
"country": "",
"artist_id": 5,
"email": "P6H77fnNvgdn@example.com",
"profile_image_url": ""
}, {
"country": "US",
"artist_id": 6,
"email": "Cjdd4gzSfKM4@example.com",
"profile_image_url": "/media/artist/zizmor_039_low_res-1239.jpg"
}, {
"country": "US",
"artist_id": 7,
"email": "m8G3gdhOQmB6@example.com",
"profile_image_url": "/media/artist/img_0930-1-7654.jpg"
}]

最佳答案

Part 1 question: How can I use forEach to loop through my array of objects to set the object property of profile_image_url which has an empty string to a default link/value("/media/artist/img_0930-1-9654.jpg").

forEach documentation

var arr = [{
"country": "",
"artist_id": 4,
"email": "LzoCqLeVpy8h@example.com",
"profile_image_url": ""
}, {
"country": "",
"artist_id": 5,
"email": "P6H77fnNvgdn@example.com",
"profile_image_url": ""
}, {
"country": "US",
"artist_id": 6,
"email": "Cjdd4gzSfKM4@example.com",
"profile_image_url": "/media/artist/zizmor_039_low_res-1239.jpg"
}, {
"country": "US",
"artist_id": 7,
"email": "m8G3gdhOQmB6@example.com",
"profile_image_url": "/media/artist/img_0930-1-7654.jpg"
}];

// e: element, i: index
arr.forEach(function(e, i) {
if (e.profile_image_url === '') {
arr[i].profile_image_url = '/media/artist/img_0930-1-9654.jpg';
}
});

console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 2) + '</pre>');

Part 2 question: Which one am I better off? Iterate through forEach or regular for loop?

使用 forEach 的好处是可以从数组中获取 indexvalue。您不必显式设置索引 var i = 0;,从数组 arr[i] 中获取值并使用 arr.length 用于迭代。

检查 http://blog.niftysnippets.org/2012/02/foreach-and-runtime-cost.html

关于javascript - 如何通过对象数组运行 forEach 并为具有空字符串的对象属性设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983982/

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