[英]Convert Nested object into custom array of objects: Javascript
I am having array of objects that look like this我有一组看起来像这样的对象
const test = {
a: { name: "A", selected: [1, 2, 3], display: [1, 2, 3] },
b: { name: "B", selected: [4, 5, 6], display: [4, 5, 6] },
c: { name: "C", selected: [7, 8, 9], display: [7, 8, 9] },
d: { name: "D", selected: [], display: [] }
};
I want the above to be converted as below我希望将上面的内容转换如下
const output = [
{ field: "A", selectedValues: [1, 2, 3] },
{ field: "B", selectedValues: [4, 5, 6] },
{ field: "C", selectedValues: [7, 8, 9] }
];
Basically key in the input object to be made as field
in the final object of that array and selected
in input object should be made as selectedValues
in the final object. Note only the object that has some entries selected
should be put into final arrray基本上键入输入 object 作为该数组最后 object 中的
field
并在输入 object 中selected
应该作为最终 object 中的selectedValues
。注意只有选择了一些条目的selected
应该放入最终数组
Also when all the objects in the input object have selected
as empty then just return empty array else return the above output.此外,当输入 object 中的所有对象都
selected
为空时,则只返回空数组,否则返回上面的 output。
Code that I tried我试过的代码
const result = Object.entries(test).map(([name, v]) => ({
field: name,
selectedValues: v
}));
console.log(result);
Because you want因为你想要
selected in input object should be made as selectedValues in the final object.
selected in input object 应作为最终 object 中的 selectedValues。
you should navigate to the .selected
property (the subarray) while mapping, instead of referencing the whole object. Afterwards, filter by whether that array has any values in it.您应该在映射时导航到
.selected
属性(子数组),而不是引用整个 object。之后,根据该数组是否包含任何值进行过滤。
const test = { a: { name: "A", selected: [1, 2, 3], display: [1, 2, 3] }, b: { name: "B", selected: [4, 5, 6], display: [4, 5, 6] }, c: { name: "C", selected: [7, 8, 9], display: [7, 8, 9] }, d: { name: "D", selected: [], display: [] } }; const result = Object.entries(test).map(([name, obj]) => ({ field: name, selectedValues: obj.selected })).filter(({ selectedValues }) => selectedValues.length); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.