1

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.

4 Answers 4

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I get this error: This expression is not callable. Type 'String' has no call signatures. My type is: { [key: string]: string; }
Can you post the piece of code that returns this error? It should work just fine. Maybe it's an older javascript version?
1

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)

Comments

0

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) 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.