Categories
JavaScript Answers

How to fix push to Vuex store array not working in Vue?

To fix push to Vuex store array not working in Vue, we commit a mutation.

For instance, we write

const store = new Vuex.Store({
  state: {
    customers: [{ id: "1", name: "user 1" }],
  },
  mutations: {
    addCustomer: (state, customer) => {
      state.customers.push(customer);
    },
  },
})

to define our Vuex store with the addCustomer mutation.

In it, we call state.customers.push to append customer as the last item of the customers state.

Then we write

store.commit("addCustomer", { id: "2", name: "User 2" });

to call store.commit with the name of the mutation to commit and the object we want to append to the state.

Categories
JavaScript Answers

How to update if exists or add new element to array of objects with JavaScript?

To update if exists or add new element to array of objects with JavaScript, we can check if the index of the item that matches our condition exists.

For instance, we write

const upsert = (array, element) => {
  const i = array.findIndex((_element) => _element.id === element.id);
  if (i > -1) {
    array[i] = element;
  } else {
    array.push(element);
  }
};

const array = [
  { id: 0, name: "Apple", description: "fruit" },
  { id: 1, name: "Banana", description: "fruit" },
  { id: 2, name: "Tomato", description: "vegetable" },
];

upsert(array, { id: 2, name: "Tomato", description: "fruit" });

to define the upsert function.

In it, we call array.findIndex to find the element in array that matches the id value.

If it exists, then i is bigger than -1 and we assign the element to that index.

Otherwise, we call push to append element as the last item.

Categories
JavaScript Answers

How to filter strings in array based on content with JavaScript?

To filter strings in array based on content with JavaScript, we use the filter method.

For instance, we write

const PATTERN = /bedroom/;
const filtered = myArray.filter((str) => {
  return PATTERN.test(str);
});

to call myArray.filter with a callback that calls PATTERN.test to check if str matches the PATTERN regex pattern.

An array with the strings that matches PATTERN is returned.

Categories
JavaScript Answers

How to access first element of JSON object array with JavaScript?

To access first element of JSON object array with JavaScript, we use index 0.

For instance, we write

const req = { events: [{ event: "inbound", ts: 1426249238 }] };
console.log(req.events[0]);

to get the req.events array property and get its first item with index 0 in the square brackets.

Categories
JavaScript Answers

How to check if an array item is set in JavaScript?

To check if an array item is set in JavaScript, we use the in operator.

For instance, we write

const assocPagine = {
  home: 0,
  about: 1,
  work: 2,
};

if ("work" in assocPagine) {
  // ...
}

to check if the work property is in the assocPagine object as a property in the object itself or as an inherited property.