如何将包含对象的数组重构为指定格式?附示例
重构包含对象的数组为目标格式
这问题我熟,用JavaScript的数组方法就能轻松搞定!咱们直接看代码和逻辑:
首先给定你的原始数据:
const foobar = [ { "foo": { "title": "example title foo", "desc": "example description foo" } }, { "bar": { "title": "example title bar", "unnecessary": "this is not needed", "desc": "example description bar" } } ];
接下来用几行代码就能完成转换:
const result = foobar.map(item => { // 取出每个元素里唯一的嵌套对象 const { title, desc } = Object.values(item)[0]; // 用计算属性名生成目标格式的对象 return { [title]: desc }; });
代码拆解说明
foobar.map(...):遍历原数组的每一项,把每一项转换成我们需要的格式Object.values(item)[0]:因为原数组的每个元素都是只有一个键的对象,Object.values(item)会把这个对象的值转成数组,取第一个元素就是我们要的包含title和desc的嵌套对象const { title, desc } = ...:从嵌套对象里解构出需要的title和desc,自动忽略其他不需要的属性(比如第二个元素里的unnecessary){ [title]: desc }:ES6的计算属性名语法,把title的实际值作为新对象的键,desc的值作为对应的值
运行这段代码后,result就是你想要的理想格式:
[ {"example title foo": "example description foo"}, {"example title bar": "example description bar"} ]
如果原数组里的元素可能存在多个键的情况(虽然你的示例里没有),可以调整逻辑来处理,但按你的需求,上面的代码完全够用啦!
内容的提问来源于stack exchange,提问作者Remi
相关产品推荐
相关产品推荐

