首页 > 解决方案 > How to update key values behalf of Id's

问题描述

I have these JavaScript objects

var oldObject=[{ 
            id:1,
            key:'name', 
            fiendSize:'6', 
            fromPlaceHolder:'', 
            fieldInstruction:'',
            filedType:'input', 
            lable:"Single Line ", 
            type:'text', 
            formValidation: {
                required:false
            }
        }];


var newObject=  { 
            id:1,
            key:'name', 
            fiendSize:'12', 
            fromPlaceHolder:'Enter Your Name', 
            fieldInstruction:'please Enter string only',
            filedType:'input', 
            lable:"Single Line ", 
            type:'text', 
            formValidation: {
                required:true
            }
        };

I need to replace/update the oldObject value with newObject value from with the same id.

So here is the result I want to get:

var oldObject = [{ 
            id:1,
            key:'name', 
            fiendSize:'12', 
            fromPlaceHolder:'Enter Your Name', 
            fieldInstruction:'please Enter string only',
            filedType:'input', 
            lable:"Single Line ", 
            type:'text', 
            formValidation: {
                required:true
            }]

How can I implement it using JavaScript in react js ?

标签: javascriptarraysreactjsobject

解决方案


你可以Object.entries()像这样使用:

var oldObject = [{
  id: 1,
  key: 'name',
  fiendSize: '6',
  fromPlaceHolder: '',
  fieldInstruction: '',
  filedType: 'input',
  lable: "Single Line ",
  type: 'text',
  formValidation: {
    required: false
  }
}];


var newObject = {
  id: 1,
  key: 'name',
  fiendSize: '12',
  fromPlaceHolder: 'Enter Your Name',
  fieldInstruction: 'please Enter string only',
  filedType: 'input',
  lable: "Single Line ",
  type: 'text',
  formValidation: {
    required: true
  }
};

let result = [{}];
for (const [key, value] of Object.entries(oldObject[0])) {
  result[0][key] = newObject[key];
}
console.log(result);

参考:

PS我使用了新对象,但您可以更新旧对象,并且我对数组编号进行了硬编码,因此如果您有超过 1 个,则需要使用for-loop.


推荐阅读