简体   繁体   English

嵌套对象:使用相同的名称更新所有属性

[英]Nested object: Update all attributes with same names

I have a quit complex object with multiple nested objects. 我有多个嵌套对象的退出复杂对象。 This object i want to copy and update all id attributes. 我想复制和更新所有id属性的对象。

So this: 所以这:

{
  id: 1,
  name: "A",
  car: {
    id: 2,
    vendor: "xy"
    }
  ..
}

should become this: 应该变成这个:

{
  id: 6,
  name: "A",
  car: {
    id: 7,
    vendor: "xy"
    }
  ..
}

Is there a way to this in a short and generic way with JavaScript (TypeScript)? 使用JavaScript(TypeScript)是否有一种简短而通用的方法?

Update: What I did so far: 更新:到目前为止我做了什么:

const a = new MyClass();
a.id = uuid();
a.name = "A"
a.car = new Car();
a.car.id = uuid();
a.car.vendor = "xy"

//copy a
const b = JSON.parse(JSON.stringify(a));

All I want to do is increase all ids in b by 5. 我要做的就是将b中的所有id增加5。

You can loop through all the items in b and do two things. 您可以遍历b所有项目并做两件事。 If it's an id property, change it (add 5). 如果它是一个id属性,请将其更改(添加5)。 If it's an object, loop through and check both the same conditions (recursive function). 如果是对象,请遍历并检查两个相同的条件(递归函数)。 Here's how you could do it: 您可以按照以下方式进行操作:

function checkObject(obj) {
    Object.keys(obj).forEach(function(prop) { 
        if (typeof obj[prop] == "object" && prop !== null) { 
            checkObject(obj[prop]);
        }
        else if (prop == "id") {
            obj[prop] += 5;
        }
    })
}

Then you'd call it like so: 然后,您可以这样称呼它:

 function checkObject(obj) { Object.keys(obj).forEach(function(prop) { if (typeof obj[prop] == "object" && prop !== null) { checkObject(obj[prop]); } else if (prop == "id") { obj[prop] += 5; } }) } var b = { id: 1, name: "A", car: { id: 2, vendor: "xy" } } checkObject(b); console.log(b); 

Here is a function that clones the original object into a new one where each id property receives a new value generated by a given uuid function: 这是一个将原始对象克隆到新对象的函数,其中每个id属性都会接收由给定uuid函数生成的新值:

 function assignId(data, uuid) { return Object(data) !== data ? data : Object.assign({}, ...Object.entries(data).map( ([k, v]) => ({ [k]: k === "id" ? uuid() : assignId(v, uuid) }) )); } // Example use: function uuid() { return uuid.next = (uuid.next || 1000) + 1; } const a = { id: 1, name: "A", car: { id: 2, vendor: "xy" } }; const b = assignId(a, uuid); console.log(b); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM