Javascript change array

If I have an array that looks like this:

[
   {
       key: some_key,
       payload: { ... }
   }, 
   {
       key: some_key,
       payload: { ... }
   }, 
   {
       key: some_key,
       payload: { ... }
   }, 
   ...
]

      

and I want to find something using a key and then change the payload.

Is there any way other than iterating through the array?

I have a few concerns about iteration

  • This array is used by many async functions, I am concerned that the index might be invalidated by some other functions during iteration.
  • Iteration can lead to performance degradation.

I was thinking about using an immutable object there, but converting to an array before every re-render doesn't look very efficient.

Any good idea?

+3


source to share


6 answers


Another approach would be to pre-assemble the map using the key of all your items. And pass it through the array.

{
  some_key: {
    key: some_key,
    payload: {}
  },
  some_other_key: {
    key: some_other_key,
    payload: {}
  },
  ...
}

      

You still have the array as another representation of your data. The actual items would be exactly the same, because the map would just refer to the real items in the list, but you could have the fastest performance available without searching at all.



This example shows that the actual payload is all the same data, just a different (indexed) view.

const array = [
  { key: 'one' },
  { key: 'two' }
];

const map = array.reduce((acc, item) => {
  acc[item.key] = item;
  return acc;
},{});

array[0] === map.one // true

      

+1


source


Its just basic computer science. Unless you know things like a start / end index that is at least close to the range you would expect from an item, you need to search the entire space.



For your purposes, it's easy enough to use Array.filter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

0


source


Instead of using an iterated array, just enter values ​​by key.

var hashtable = {};

// Setting a value...
hashtable["key"] = someValue;

// Getting a value...
var somePayload = hashtable["key"];

      

You can iterate over an associative array very easily, and if for some reason you cannot just change your array to associative, your simplest solution is to just store an additional associative array as an index with your key.

Here's a tutorial on associative arrays in JavaScript . Good luck.

0


source


Finding an array element when you don't know its position should be linear at best. In the worst case, you still need to check every item.

Since the array is used by multiple async functions, you can still create a mechanism that will affect the array in a specific order, regardless of the order in which the actual async operations are performed.

Promises are a natural application here.

const array = [];

// these operations start at the same time
const p1 = new Promise(resolve => resolve(1));
const p2 = new Promise(resolve => resolve(2));

// no matter which one finishes first,
// we process p2 before p1 because of
// the way we build the chain
p2
.then(p2Result => {
  array.push(p2Result)
  return p1;
})
.then(p1Result => {
  array.push(p1Result);
  return array;
})
.then(console.log);
      

Run codeHide result


0


source


There are many ways map

var arr = [
   {
       key: 1,
       payload: { }
   }, 
   {
       key: 2,
       payload: { }
   }, 
   {
       key: 3,
       payload: {}
   }
];

arr.map(function(e, i) {
  if(e.key === 1) {
    e.payload = {id: 11, name: "someone" }
  }
})
console.log(arr)
      

Run codeHide result


through findIndex

var arr = [
       {
           key: 1,
           payload: { }
       }, 
       {
           key: 2,
           payload: { }
       }, 
       {
           key: 3,
           payload: {}
       }
    ];
    var elementIndex = arr.findIndex(x => x.key === 1);
    if(elementIndex > -1)
        arr[elementIndex].payload = {id: 11, name: "someone"};
    console.log(arr)
      

Run codeHide result


And depending on your needs, there are more options :)

0


source


If you want to change the way your data is structured, you can do something like this using Map :

var values = [
   {
       key: '4',
       payload: 'a'
   }, 
   {
       key: '5',
       payload: 'b'
   }, 
   {
       key: '6',
       payload: 'c'
   }, 
];

values = new Map(values.map(elem => [elem.key, elem]))

values.set('5', {key: '5', payload: 'x'});

console.log(values.get('5'));
      

Run codeHide result


0


source







All Articles