Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save monkeymars/9619d78418be07865f09a4feb9249bd5 to your computer and use it in GitHub Desktop.

Select an option

Save monkeymars/9619d78418be07865f09a4feb9249bd5 to your computer and use it in GitHub Desktop.
es6 spread immutable cheatsheet

filter object with Array.prototype.reduce

const items = {
  1: {
    id: 1,
    name: "Goran"
  }, 
  2: {
    id: 2,
    name: "Petar"
  }
};

const filterId = 1;

const filteredItems = Object.keys(items).reduce( (accumulator, key) => (
   items[key].id === filterId ? accumulator : {
       ...accumulator,
       [key]: items[key]
   }                                        
), {});

console.log(filteredItems);
/*
  {
    2: {
      id: 2,
      name: "Petar"
    }
  }
  }
*/

update array using Array.prototype.slice

var state = [
  {name: "Goran"},
  {name: "Peter"}
]

// find index manually
// let index = state.findIndex(({name}) => name === "Peter");
var index = 1;
var field = 'name';
var value = 'Zika';

var newState = [
  ...state.slice(0, index),
  {
    ...state[index],
    [field]: value
  },
  ...state.slice(index + 1)
];

console.log(newState);
/*
  [
    {name: "Goran"},
    {name: "Zika"}
  ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment