I have a key value pair:
`{good: 'value1', key2: 'value2': key3: 'value3'}
I want to convert it as the following:
[{key: 'good', value:'value1'}, {key: 'key2', value: 'value2'}, {key: 'key3', value: 'value3']
So far, I am able to convert them into an array with Object.entries, but I am unable to get my desired result.
CodePudding user response:
You can do it like this:
const data = {good: 'value1', key2: 'value2', key3: 'value3'};
const result = [];
Object.keys(data).forEach(key => {
result.push({key, value: data[key]})
})
console.log(result)
CodePudding user response:
There exists a method Object.entries
that turns object into list of keys and values already, mapping it to match your required format should not be difficult.
const data = {good: 'value1', key2: 'value2', key3: 'value3'};
const result = Object.entries(data).map(([key, value]) => ({key, value}))
console.log(result)
CodePudding user response:
To transform arrays, javascript provides a variety of array methods. map, foreach, reduce. etc. (Read more)
Object.entries( data )
converts your object into an array of arrays where each inner array is a key-value pair like this
[ [key1, value1], [key2, value2] ....]
. (Read More)
Your usecase:
const data = { good: 'value1', key2: 'value2', key3: 'value3' };
const entries = Object.entries(data);
// [ ["good","value1"], ["key2","value2"],["key3","value3"] ]
// Map those entries to your desired form.
const results = entries.map( entry => ({ key: entry[0], value: entry[1] }) ) ;
// Or leverage the destructuring fetaure
// const results = entries.map( ([key, value]) => ({ key, value }) ) ;
console.log(results)
CodePudding user response:
In case if you are interested in fast solution:
type Values<T> = T[keyof T]
type Mapper<T> = {
[Prop in keyof T]: { key: Prop, value: T[Prop] }
}
type Convert<T> = Array<Values<Mapper<T>>>
function convert<
Prop extends string,
Value extends string,
Obj extends Record<Prop, Value>
>(obj: Obj): Convert<Obj>
function convert<
Prop extends string,
Value extends string,
Obj extends Record<Prop, Value>
>(obj: Obj) {
const result: {
key: Extract<keyof Obj, string>;
value: Obj[Extract<keyof Obj, string>];
}[] = []
for (let prop in obj) {
result.push({
key: prop,
value: obj[prop]
})
}
return result
}
const result = convert({ good: 'value1', key2: 'value2', key3: 'value3' })
const first = result[0]
if (first.key === 'good') {
// {
// key: "good";
// value: "value1";
// }
first
}
Cons:
convert
function creates internal result
variable and mutates it. It is possible to use recursion instead of mutation result
but I'm not sure this trade of worth it.
Pros
Faster than entries & map
Convert
types maps type of argument to the type you want to achieve but only in type scope, whereas function maps argument in runtime scope.
If performance is not critical, you probably should stick with other solution where Object.entries
is used