【发布时间】:2020-05-16 15:53:10
【问题描述】:
我有一个带有子数组的数组,我正在尝试向每个子数组添加一个新属性 title。我有一个实现,但不是将标题添加到每个子数组,而是将其放在数组的末尾
[
{ nextEpisodeDate: null },
{
episode: 12,
id: '28800/tokyo-ghoul-12',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/12/th_3.jpg'
},
{
episode: 11,
id: '28459/tokyo-ghoul-11',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/11/th_3.jpg'
},
{
episode: 10,
id: '28001/tokyo-ghoul-10',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/10/th_3.jpg'
},
{
episode: 9,
id: '27741/tokyo-ghoul-9',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/9/th_3.jpg'
},
{
episode: 8,
id: '27092/tokyo-ghoul-8',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/8/th_3.jpg'
},
{
episode: 7,
id: '26689/tokyo-ghoul-7',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/7/th_3.jpg'
},
{
episode: 6,
id: '26529/tokyo-ghoul-6',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/6/th_3.jpg'
},
{
episode: 5,
id: '26431/tokyo-ghoul-5',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/5/th_3.jpg'
},
{
episode: 4,
id: '26373/tokyo-ghoul-4',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/4/th_3.jpg'
},
{
episode: 3,
id: '26278/tokyo-ghoul-3',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/3/th_3.jpg'
},
{
episode: 2,
id: '26188/tokyo-ghoul-2',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/2/th_3.jpg'
},
{
episode: 1,
id: '26103/tokyo-ghoul-1',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/1/th_3.jpg'
}
]
我想实现以下目标
{
episode: 12,
title: '......'
id: '28800/tokyo-ghoul-12',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/12/th_3.jpg'
},
{
episode: 11,
title: '......'
id: '28459/tokyo-ghoul-11',
imagePreview: 'https://cdn.animeflv.net/screenshots/1415/11/th_3.jpg'
},
实施
* @param {Object} obj The original object
* @param {String} key The key for the item to add
* @param {Any} value The value for the new key to add
* @param {Number} index The position in the object to add the new key/value pair [optional]
var addToObject = function (obj, key, value, index) {
// Create a temp object and index variable
var temp = {};
var i = 0;
// Loop through the original object
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// If the indexes match, add the new item
if (i === index && key && value) {
temp[key] = value;
}
// Add the current item in the loop to the temp obj
temp[prop] = obj[prop];
// Increase the count
i++;
}
}
// If no index, add to the end
if (!index && key && value) {
temp[key] = value;
}
return temp;
};
let list = addToObject(listByEps, 'title' , '....', 0)
【问题讨论】:
-
据我所知,
i === index对除第一个对象以外的每个对象都失败,这不是情节对象。此外,这是一个对象数组,而不是子数组。 -
我是否正确理解您想为数组中的每个元素(具有情节)属性赋予另一个名为 title 的属性?你想在不同的对象中使用不同的标题值吗?不同标题值的来源是什么?向对象添加道具非常容易,甚至是数组中的道具。这个问题无法理解的是标题数据的来源,以及它与现有对象的关系
-
您好,对于每个子数组,我想传递一个名为 title 的新属性,我遇到的问题是它没有更新 title 属性的值,它总是向我显示相同的标题。您可以在底部看到一个临时解决方案。但它显示了相同的标题。
标签: javascript arrays loops properties sub-array