删除键:嵌套对象中的值对

时间:2020-04-19 11:17:09

标签: javascript object lodash

我有这个对象:

const myObject = {
  myNestedObject1: {
    key1: "key1",
    key2: "key2",
    key3: "key3"
  },
  myNestedObject2: {
    key1: "key1",
    key2: "key2",
    key3: "key3"
  },
  myNestedObject3: {
    key1: "key1",
    key2: "key2",
    key3: "key3"
  }
}

我想获得一个新的相似对象,但没有键值对key2: "key2",并且不改变原始对象。

const myObject = {
  myNestedObject1: {
    key1: "key1",
    key3: "key3"
  },
  myNestedObject2: {
    key1: "key1",
    key3: "key3"
  },
  myNestedObject3: {
    key1: "key1",
    key3: "key3"
  }
}

是否有任何简便的方法?可能是洛沙特?

谢谢!


根据要求,这是我要尝试的:

const myObject = {
  myNestedObject1: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
  myNestedObject2: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
  myNestedObject3: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
};

 result = _.transform(
  Object.assign({}, myObject),
  (acc, value, key) => {
    delete value["key2"]

    acc[key] = value;
  },
  {}
);

会产生所需的对象,但会改变原始对象。

2 个答案:

答案 0 :(得分:1)

您可以使用Object.entries()Object.fromEntries()Array.prototype.map()来做到这一点。

const myObject = {myNestedObject1: {key1: "key1",key2: "key2",key3: "key3"}, myNestedObject2: {key1: "key1",key2: "key2",key3: "key3"}, myNestedObject3: {key1: "key1",key2: "key2",key3: "key3"}};

const res = Object.fromEntries(Object.entries(myObject).map(([key, value]) => {
   const {key2, ...rest} = value; // Get all the keys except key2 at ...rest
   return [key, rest];
}));

console.log(res);
.as-console-wrapper {min-height: 100% !important; top: 0;}

更新

在这里,我建议使用reduce的另一种方法。

const myObject = {myNestedObject1: {key1: "key1",key2: "key2",key3: "key3"}, myNestedObject2: {key1: "key1",key2: "key2",key3: "key3"}, myNestedObject3: {key1: "key1",key2: "key2",key3: "key3"}};

const res = Object.entries(myObject).reduce((acc, [key, value]) => {
	const {key2, ...rest} = value;
	return {...acc, [key]: rest}
}, {});

console.log(res);
.as-console-wrapper {min-height: 100% !important; top: 0;}

答案 1 :(得分:1)

您可以简单地遍历对象并删除对象属性:

const myObject = {
  myNestedObject1: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
  myNestedObject2: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
  myNestedObject3: {
    key1: "key1",
    key2: "key2",
    key3: "key3",
  },
};
const result = JSON.parse(JSON.stringify(myObject)); //make a shallow copy of the object
for(let o in result){
  delete result[o]['key2'];
}
console.log(result);