Add property to object based on its data

I have a list of records (CSV to JSON) where each row has a variable numbers of attributes in its columns. It could be something like Attribute 1 name and Attribute 1 value, and so on for 2, 3, 4... On the output object, I'd like to make a Record where the name is the key, and it points to an object based on the attribute data (name and value in this case). So if the product type is (simplified):
const product = type({
id: "string",
attributes: type({
"[string]": type({
name: "string",
value: "string"
}),
})
})
const product = type({
id: "string",
attributes: type({
"[string]": type({
name: "string",
value: "string"
}),
})
})
Then there are two problems: 1. The attributes property doesn't exist on the type, so it needs to be added. Right now I get a must be an object (was missing) error. How to add that without any type checking, so to speak? 2. Then I guess I need to pipe the product type and parse all the attributes there, so they can be added to the attributes property, is that right?
3 Replies
ciscoheat
ciscoheatOP2w ago
I handled it like this:
const product = type("Record<string, unknown>").pipe(r => {
// Parse properties of r, create attributes
r.attributes = ...;
return r;
}).to({
id: "string",
attributes: type({
"[string]": type({
name: "string",
value: "string"
}),
})
})
const product = type("Record<string, unknown>").pipe(r => {
// Parse properties of r, create attributes
r.attributes = ...;
return r;
}).to({
id: "string",
attributes: type({
"[string]": type({
name: "string",
value: "string"
}),
})
})
ssalbdivad
ssalbdivad2w ago
Seems reasonable from what I understand! Quick note- you don't need to call type for nested levels- once you're parsing a definition, you can just define nested definitions directly.
ciscoheat
ciscoheatOP2w ago
Oh that's nice, thanks It's so cool that Arktype turns into a most convenient and robust CSV->JSON parser ☺️

Did you find this page helpful?