[英]How to filter objects based on different keys and save the results into an array
I want to filter object based on key我想根据密钥过滤 object
var form = { code_ 1 : "C",
option_1 : "1321",
code_ 2 : "A",
option_2 : "1521",
code_ 3 : "B",
option_3 : "1121",
...
}
I want filter object and save into array.我想过滤 object 并保存到数组中。
code = ["C", "A", "B"]
option = ["1321", "1521", "1121"]
but I don't how because there is a number in the attribute name.但我不知道,因为属性名称中有一个数字。
You could use Object.entries to transform the form
to array of key-value pairs您可以使用 Object.entries 将
form
转换为键值对数组
After that, iterate through the pair, check the key string and push the value to the propriated array之后,遍历该对,检查键字符串并将值推送到专有数组
const code = []; const option = []; var form = { code_1: "C", option_1: "1321", code_2: "A", option_2: "1521", code_3: "B", option_3: "1121", }; Object.entries(form).forEach(([key, value]) => { if (key.startsWith("code")) { code.push(value); } else if (key.startsWith("option")) { option.push(value); } }); console.log({ code, option, });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.