0

我想使用 immutability-helper 进行两种类型的操作,但我非常卡住。

我有这些数据,模拟来自 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,它是声音数组中对象的属性,是否有使用更新的简洁方法?如果是这样,我很想看到它。否则,我将使用 array.findIndex 来获取索引。

我真的很感谢任何帮助,这个周末我被困住了。

4

1 回答 1

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 );

按编号

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 );

于 2018-09-24T00:45:24.740 回答