[英]How can an array containing objects be restructured in a preferred format?
Given the following example:给出以下示例:
foobar: [
{
"foo": {
"title": "example title foo"
"desc": "example description foo"
}
},
{
"bar": {
"title": "example title bar",
"unnecessary": "this is not needed"
"desc": "example description bar",
}
}
]
How to format this array containing objects that you get the following result:如何格式化这个包含对象的数组,你会得到以下结果:
[
{"example title foo": "example description foo"},
{"example title bar": "example description bar"}
]
You could use Object.values
and map
.您可以使用Object.values
和map
。 Use Computed property names to create the desired object使用计算属性名称创建所需的对象
let foobar = [{"foo":{"title":"example title foo","desc":"example description foo"}},{"bar":{"title":"example title bar","unnecessary":"this is not needed","desc":"example description bar"}}] let output = foobar.map(a => { let { title, desc } = Object.values(a)[0]; return { [title] : desc } }) console.log(output)
You could get a single value's object, destructure it and map the wanted style.您可以获取单个值的对象,对其进行解构并映射所需的样式。
var foobar = [{ foo: { title: "example title foo", desc: "example description foo" } }, { bar: { title: "example title bar", unnecessary: "this is not needed", desc: "example description bar" } }], pattern = ({ title, desc }) => ({ [title]: desc }), result = foobar.map(o => pattern(Object.values(o)[0])); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.