I'm trying to concat data that have similar key names into string separated by ,
.
What I mean by similar keys is:
name.0.id
name.1.id
...
Basically I have an array of array.
[
[array(6)]
[array(9)]
[array(10)]
]
the arrays look like the following:
[
[
"id",
10
],
[
"group_name",
"Test"
],
[
"admin",
"Nobody"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
4
],
[
"created_by.email",
"[email protected]"
]
],
[
[
"id",
8
],
[
"group_name",
"Datass"
],
[
"admin",
"[email protected]"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
11
],
[
"created_by.email",
"[email protected]"
],
[
"students.0.email",
"[email protected]"
],
[
"students.1.email",
"[email protected]"
],
[
"names.0.id",
13
],
[
"names.1.id",
35
]
]
I have a fixed keys that have all the keys I need, like:
const fixed = [
"id",
"group_name",
"admin",
"email_address",
"org.id",
"created_by.email",
"students",
"names"
]
I would need to get those arrays and create a new array, with the same size as the fixed keys array, but the data that contains 0.id
or 1.id
... will be concataned into string separated by commas. And if the array that is being filtered doens't contain that data, I will insert an empty string
This is what I'm attempting:
[
[
"id",
10
],
[
"group_name",
"Test"
],
[
"admin",
"Nobody"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
4
],
[
"created_by.email",
"[email protected]"
],
[
"students",
""
],
[
"names",
""
],
],
[
[
"id",
8
],
[
"group_name",
"Datass"
],
[
"admin",
"[email protected]"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
11
],
[
"created_by.email",
"[email protected]"
],
[
"students",
"[email protected],[email protected]"
],
[
"names",
"13,35"
],
]
I Have used regex to match the names:
/(names)(.)([0-9])(.)(id)($)/.test(key)
CodePudding user response:
You can do something like this
const extractData = (data, fields) => data.map(d => {
const obj = Object.fromEntries(d)
const keys = Object.keys(obj)
return fields.map(key => [
key,
keys.filter(k => k.startsWith(key)).map(k => obj[k]).join(',')
])
})
const fixed = [
"id",
"group_name",
"admin",
"email_address",
"org.id",
"created_by.email",
"students",
"names"
]
const data = [
[
[
"id",
10
],
[
"group_name",
"Test"
],
[
"admin",
"Nobody"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
4
],
[
"created_by.email",
"[email protected]"
]
],
[
[
"id",
8
],
[
"group_name",
"Datass"
],
[
"admin",
"[email protected]"
],
[
"email_address",
"[email protected]"
],
[
"org.id",
11
],
[
"created_by.email",
"[email protected]"
],
[
"students.0.email",
"[email protected]"
],
[
"students.1.email",
"[email protected]"
],
[
"names.0.id",
13
],
[
"names.1.id",
35
]
]
]
console.log(extractData(data, fixed))