javascript - 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 ?
解决方案
你可以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
.
推荐阅读
- scala - 为什么我无法访问对象的属性
- r - 我想用我在 R 中打印的这个循环的值创建一个 data.frame
- regex - Apache 仅重定向查询的一部分
- c# - 为什么在传递动态对象的接口类型上调用继承方法时会引发 RuntimeBinderException?
- javascript - 动态改变第n个孩子的数量
- javascript - 选择和取消选择不适用于js中动态创建的复选框
- python-3.x - 从 DateTimeCtrl WXPython 中检索日期
- adobe - 通过在 Adobe Acrobat Pro 中添加白色区域来更改页面大小
- angular - angular-material mdDialog 有时会立即显示和隐藏
- java - 如何在睡眠方法期间关闭扫描仪?