如何替换数组中的对象值?

时间:2020-08-11 22:42:03

标签: javascript reactjs

我为此寻找方向感到困惑。我有一个状态对象:

const state = [
{type: 'Primary', number: 123456}, 
{type: 'Mobile', number: 789012}
] 

我有一个功能,可以为我提供oldValuenewValueindex的更新值。

例如,如何在“ Mobile”对象中替换特定的number值并返回新数组?

5 个答案:

答案 0 :(得分:1)

如果您有state数组index,则需要更改newValueoldValue

const newState = state.map((obj, i) => { 
  if(i === index && obj.number === oldValue) {
    let newObj = { ...obj };
    newObj.number = newValue;
    return newObj;
  }
  return obj;
}
 

答案 1 :(得分:0)

const state = [
{type: 'Primary', number: 123456}, 
{type: 'Mobile', number: 789012}
] 

const someFunction = (state, oldValue, newValue, index) => {
let newState = state.map(e => {
if(e.type === index) e.number = newValue;
return e
})
return newState
}

const newState = someFunction(state, '', 123456, 'Mobile')

console.log(newState)

答案 2 :(得分:0)

您可以使用array.find()查找相应的对象并替换特定的值:

const state = [
{type: 'Primary', number: 123456}, 
{type: 'Mobile', number: 789012}
]

// This will find and return the FIRST item that matches, or undefined if none are found
const ObjectToChange = state.find(elem => elem.type === 'Mobile')
if (ObjectToChange != undefined)
  ObjectToChange.number = 42;

console.log(state);

答案 3 :(得分:0)

如果您要更改值,请执行以下操作:

const state = [
{type: 'Primary', number: 123456}, 
{type: 'Mobile', number: 789012}
];

state[state.findIndex(item=>item.type==='Mobile')]={type:'Mobile',number:1111}

console.log(JSON.stringify(state,null,2));

答案 4 :(得分:0)

您可以使用Array.map来返回更新后的数组,如下所示:

const updateFunction = (state, oldValue, newValue, index) => {
   return state.map((stateObject, i) => i === index ? ({ ...stateObj, number: newValue }) : stateObject);
}
相关问题