0

I have an array like this:

[
  {
    "fact": "field1",
    "operator": "equal",
    "value": "field1_value"
  },
  {
    "fact": "field2",
    "operator": "equal",
    "value": "field2_value"
  },
  {
    "fact": "field3",
    "operator": "equal",
    "value": "field3_value"
  },
  {
    "fact": "field4",
    "operator": "equal",
    "value": "field4_value"
  },
  {
    "fact": "field5",
    "operator": "equal",
    "value": "field5_value"
  }
]

I want to build an object like this:

{
  field1: field1_value,
  field2: field2_value,
  field3: field3_value,
  field4: field4_value,
  field5: field5_value,
}

I have thousands of objects in the source array and I have thousands of such arrays to work with. What's the best way to do this in typescript?

HelmBurger
  • 1,168
  • 5
  • 15
  • 35

3 Answers3

2

Something like this:

const yourJSON = [
  {
    "fact": "field1",
    "operator": "equal",
    "value": "field1_value"
  },
  {
    "fact": "field2",
    "operator": "equal",
    "value": "field2_value"
  },
  {
    "fact": "field3",
    "operator": "equal",
    "value": "field3_value"
  },
  {
    "fact": "field4",
    "operator": "equal",
    "value": "field4_value"
  },
  {
    "fact": "field5",
    "operator": "equal",
    "value": "field5_value"
  }
]

JSON.parse(yourJSON)

const newObject = {}

for (let i in yourJSON) {
  const key = yourJSON[i].fact
  const value = yourJSON[i].value
  newObject[key] = value
}

JSON.stringify(newObject)

Why for loop? Because you have thousands of such arrays like you said and for loops are faster then something like forEach and etc.

My answer is in JavaScript but TS will be pretty something like this.

Elisey
  • 137
  • 7
1

I would do it like so: Declare the interface for the layout of your fielddefinitions and then just loop over the array of those and add the fields one by one.

interface IFieldDefinition {
  fact: string;
  operator: string;
  value: string;
}

const fields: IFieldDefinition[] = [
  {
    "fact": "field1",
    "operator": "equal",
    "value": "field1_value"
  },
  {
    "fact": "field2",
    "operator": "equal",
    "value": "field2_value"
  },
  {
    "fact": "field3",
    "operator": "equal",
    "value": "field3_value"
  },
  {
    "fact": "field4",
    "operator": "equal",
    "value": "field4_value"
  },
  {
    "fact": "field5",
    "operator": "equal",
    "value": "field5_value"
  }
];

const destObject: Record<string, string> = {};

for (const field of fields) {
  destObject[field.fact] = field.value;
}
Ulrich Stark
  • 401
  • 3
  • 12
0

sweet one liner

function jsonToArray(arr: Object[]): {} {
    return Object.fromEntries(a.map(el => [el["fact"], el["value"]]));
}
RaiderB
  • 100
  • 1
  • 6