我有一个嵌套的对象,其结构如下:
let obj = {
id1: {
key1: value1,
files: {
fileid1: {},
fileid2: {}
}
},
id2: {
key1: value1,
files: {
fileid3: {},
fileid4: {}
}
}
}
我有一个现有的文件ID,我需要从该对象中找到该文件ID并更新该对象的数据。 假设我的文件ID等于 fileid3 我该怎么办?
答案 0 :(得分:1)
let obj = {
id1: {
key1: "value1",
files: {
fileid1: {},
fileid2: {}
}
},
id2: {
key1: "value1",
files: {
fileid3: {},
fileid4: {}
}
}
}
function changeObj(obj, field, value) {
Object.keys(obj).forEach(key => {
if (obj[key].files.hasOwnProperty(field))
obj[key].files[field] = value;
});
return obj;
}
console.log(changeObj(obj, "fileid3", "new Value"));
答案 1 :(得分:0)
您可以在对象的.find()
上使用Object.values()
。对于每个值(即对象),您可以检查.files
对象是否具有传递给函数的fileid
的属性。如果可以,则可以使用.hasOwnProperty()
返回true
。然后,您可以在.files[id]
的返回值上使用.find()
来获取对象:
const obj = { id1: { key1: "value1", files: { fileid1: {}, fileid2: {} } }, id2: { key1: "value1", files: { fileid3: {}, fileid4: {} } } };
const findObjectByFile = (obj, id) =>
(Object.values(obj).find(({files}) => files.hasOwnProperty(id)) || {files: {}}).files[id];
const file_obj = findObjectByFile(obj, "fileid");
file_obj.foo = "bar";
console.log(obj);
答案 2 :(得分:0)
只需使用Object.values
遍历对象的第一级,并使用files
运算符检查in
对象是否包含您要查找的属性。
let obj = {
id1: {
key1: "value1",
files: {
fileid1: {},
fileid2: {}
}
},
id2: {
key1: "value1",
files: {
fileid3: {},
fileid4: {}
}
}
};
editFileID("fileid3", "new value");
console.log(obj.id2.files.fileid3);
function editFileID(fileID, newValue) {
Object.values(obj).some(function(obj) {
if (fileID in obj.files) {
obj.files[fileID] = newValue;
return true;
}
});
}
答案 3 :(得分:0)
这是示例JSON对象:
const myJSONExample = {
id1: {
key1: "value1",
files: {
fileid1: "2",
fileid2: "3"
}
},
id2: {
key1: "value1",
files: {
fileid3: "4",
fileid4: "5"
}
}
}
现在遍历该对象,找到您的特定键并更新其值。如果键是嵌套对象,则使用递归。
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
if(key == 'fileid3'){
obj[key] = 'asd';
}
if (typeof obj[key] === 'object') {
iterate(obj[key])
}
})
}
iterate(myJSONExample);
console.log(myJSONExample);
输出:
{
id1:
{
key1: 'value1',
files:
{ fileid1: '2', fileid2: '3' }
},
id2:
{
key1: 'value1',
files:
{ fileid3: 'asd', fileid4: '5'}
}
}
fileid3
值已更新