簡體   English   中英

如何將 object 深層屬性轉換為另一個?

[英]How to convert object deep properties in to another?

以下是一個深度嵌套的 object,其屬性重復出現。

如何轉換以下深度嵌套的 object

const obj = {
    prop1: {
        properties: { value: {} },
    },
    prop2: {
        properties: { subProp: { properties: { value: {} } } },
    },
    prop3: {
        properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } },
    },
};

進入這個:

const obj = {
    prop1: { value: {} },
    prop2: { subProp: { value: {} } },
    prop3: { subProp: { subSubProp: { value: {} } } },
};

//if properties exists, else leave as it is (in each level)

您可以構建新對象並檢查該值是否為 object 以及properties是否存在。 然后使用properties或 object 進行遞歸調用。

 const removeProperties = object => Object.fromEntries(Object.entries(object).map(([key, value]) => [ key, value && typeof value === 'object'? removeProperties('properties' in value? value.properties: value): value ]) ), obj = { prop1: { properties: { value: {} } }, prop2: { properties: { subProp: { properties: { value: {} } } } }, prop3: { properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } } } }; console.log(removeProperties(obj));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

沒有Object.fromEntries

 const removeProperties = object => Object.entries(object).map(([key, value]) => [ key, value && typeof value === 'object'? removeProperties('properties' in value? value.properties: value): value ]).reduce((object, [key, value]) => ({...object, [key]: value }), {}), obj = { prop1: { properties: { value: {} } }, prop2: { properties: { subProp: { properties: { value: {} } } } }, prop3: { properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } } } }; console.log(removeProperties(obj));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以遞歸刪除它

 const obj = { prop1: { properties: { value: {} }, }, prop2: { properties: { subProp: { properties: { value: {} } } }, }, prop3: { properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } }, }, }; function converter(obj){ if(typeof obj.== "object") return Object.entries(obj),forEach(([key. value]) => { if(value.properties){ obj[key] = value.properties delete value.properties } if(typeof obj[key] === "object"){ converter(obj[key]) } }) } converter(obj) console.log(obj)

試試這個,這種遞歸方法也適用於嵌套刪除數據

const obj = {
  prop1: {
    properties: { value: {} },
  },
  prop2: {
    properties: { subProp: { properties: { value: {} } } },
  },
  prop3: {
    properties: { subProp: { properties: { subSubProp: { properties: { value: {} } } } } },
  },
};

function propsRemover(data) {
  return Object.fromEntries(Object.entries(data).map(([key, { properties }]) => [key, propsRemover({ ...properties })]));
}

console.log(JSON.stringify(propsRemover(obj)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM