我想使用不可变性辅助程序进行两种类型的操作,但是我非常困惑。
我有这些数据,模拟了API的结果:
var test_data = {
title: "Potato",
sounds: [
{ sound_name: "Fork", id: 27 },
{ sound_name: "Spoon", id: 28 },
{ sound_name: "Knife", id: 29 }
]
};
类型1-当我有索引时更改声音名称
如果我知道声音数组的索引,如何更改声音名称之一?我希望使用update(test_data,$ merge ...)。到目前为止,我所做的工作无法正常工作,因此我没有将其粘贴到这里。
类型2-当我知道ID时更改声音名称
如果我知道声音的ID(这是声音数组中对象的属性),是否有使用update的简洁方法?如果是这样,我很乐意看到。否则,我将使用array.findIndex来获取索引。
我非常感谢您的帮助,这个周末我一直被困住。
答案 0 :(得分:0)
以下是一些没有使用任何帮助程序的示例。
按索引
const test_data = {
title: "Potato",
sounds: [
{ sound_name: "Fork", id: 27 },
{ sound_name: "Spoon", id: 28 },
{ sound_name: "Knife", id: 29 }
]
};
const targetIndex = 1;
// Map the sounds, find the element which has targetIndex,
// change it with spread syntax. Return other elements as
// it is
const newSounds = test_data.sounds.map( (sound,index) => {
if( index !== targetIndex ) { return sound };
return { ...sound, sound_name: "Foo"}
});
// Create new data again with spread syntax. Keep other
// properties, update the sounds.
const newData = { ...test_data, sounds: newSounds };
console.log( "old", test_data.sounds, "\nnew", newSounds );
console.log( newData );
通过ID
const test_data = {
title: "Potato",
sounds: [
{ sound_name: "Fork", id: 27 },
{ sound_name: "Spoon", id: 28 },
{ sound_name: "Knife", id: 29 }
]
};
const targetId = 28;
// Map sounds, find the element by using id, change it
// leave others.
const newSounds = test_data.sounds.map( sound => {
if( sound.id !== targetId ) { return sound };
return { ...sound, sound_name: "Foo" };
})
const newData = { ...test_data, sounds: newSounds };
console.log( "old", test_data.sounds, "\nnew", newSounds );
console.log( newData );