How to replace an item in an array with JavaScript?

后端 未结 26 2164
执笔经年
执笔经年 2020-11-29 15:33

Each item of this array is some number.

var items = Array(523,3452,334,31, ...5346);

How do I replace some number in with array with a new on

相关标签:
26条回答
  • 2020-11-29 15:53

    Here is the basic answer made into a reusable function:

    function arrayFindReplace(array, findValue, replaceValue){
        while(array.indexOf(findValue) !== -1){
            let index = array.indexOf(findValue);
            array[index] = replaceValue;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 15:54

    ES6 way:

    const items = Array(523, 3452, 334, 31, ...5346);
    

    We wanna replace 3452 with 1010, solution:

    const newItems = items.map(item => item === 3452 ? 1010 : item);
    

    Surely, the question is for many years ago and for now I just prefer to use immutable solution, definitely, it is awesome for ReactJS.

    For frequent usage I offer below function:

    const itemReplacer = (array, oldItem, newItem) =>
      array.map(item => item === oldItem ? newItem : item);
    
    0 讨论(0)
  • 2020-11-29 15:56

    A functional approach to replacing an element of an array in javascript:

    const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];

    0 讨论(0)
  • 2020-11-29 15:59

    First method

    Best way in just one line to replace or update item of array

    array.splice(array.indexOf(valueToReplace), 1, newValue)
    

    Eg:

    let items = ['JS', 'PHP', 'RUBY'];
    
    let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')
    
    console.log(replacedItem) //['RUBY']
    console.log(items) //['JS', 'PHP', 'PYTHON']
    

    Second method

    An other simple way to do the same operation is :

    items[items.indexOf(oldValue)] = newValue
    
    0 讨论(0)
  • 2020-11-29 15:59

    Here attached the code which replace all items in array

    var temp_count=0;
    layers_info_array.forEach(element => {
         if(element!='')element=JSON.parse(element);//change this line if you want other change method, here I changed string to object
         layers_info_array[temp_count]=element;
         temp_count++;
    });
    
    0 讨论(0)
  • 2020-11-29 16:00

    Well if anyone is interresting on how to replace an object from its index in an array, here's a solution.

    Find the index of the object by its id:

    const index = items.map(item => item.id).indexOf(objectId)
    

    Replace the object using Object.assign() method:

    Object.assign(items[index], newValue)
    
    0 讨论(0)
提交回复
热议问题