immutability-helper - застрял на манипулировании простыми объектами - PullRequest
0 голосов
/ 24 сентября 2018

У меня есть два типа манипуляций, которые я хотел бы сделать с помощью 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 - Измените имя_звука, если у меня есть индекс

Если я знаю индекс массива звуков, как мне изменить одно из имен_звука?Я ожидаю использовать обновление (test_data, $ merge ...).То, что я сделал до сих пор, не работает, поэтому я не вставил его сюда.

Тип 2 - Измените имя_звука, когда я знаю идентификатор

Если я знаю идентификатор звука, который является свойством объекта в массиве звуков, есть ли краткий способ использования обновления?Если это так, я бы хотел увидеть это.В противном случае я буду использовать array.findIndex для получения индекса.

Я очень ценю любую помощь, я застрял на этих выходных.

1 Ответ

0 голосов
/ 24 сентября 2018

Вот примеры без использования какого-либо помощника.

По индексу

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