gpt4 book ai didi

javascript - 如何将数组值放入嵌套数组中

转载 作者:行者123 更新时间:2023-11-28 18:31:14 24 4
gpt4 key购买 nike

var collection = {
"2548": {
"album": "Slippery When Wet",
"artist": "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
"2468": {
"album": "1999",
"artist": "Prince",
"tracks": [
"1999",
"Little Red Corvette"
]
},
"1245": {
"artist": "Robert Palmer",
"tracks": [ ]
},
"5439": {
"album": "ABBA Gold"
}
};

var collectionCopy = JSON.parse(JSON.stringify(collection));

function updateRecords(id, prop, value) {
if (!value) delete collection[id][prop];
if (!!value && prop === 'tracks'){

collection[id][prop] = []; // Solve my problem

collection[id][prop].push(value);
}
if (!!value && prop === 'artist') collection[id][prop] = value;
return collection;
}

updateRecords(5439, "tracks", "Take a Chance on Me");

这是返回错误的原始代码。这是经过编辑的,请忽略这个问题,谢谢。尝试修复“push 是未定义函数”的错误。如果未定义,则无法将值推送到数组对象上,因此我将

集合[id][prop] = [];//解决我的问题

避免出现错误,提示此行代码中未定义推送....

集合[id][prop].push(value);

最佳答案

尝试以下

collection["5439"].tracks = ["some info", "some more info"];

关于javascript - 如何将数组值放入嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968963/

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