Javascript - split an array into complex section list with titles

Viewed 81

I need to convert fields array into a section list format. The example of an expected output can be found in the reproduction below.

Basically, the fieldName should be mapped with the corresponding value in values object. I'm currently stuck with it and cannot figure out of how to concat these two sources of data - values and fields.

How can this be done? Thank you in advance?

Reproduction example with expected output:

const values = {
  Num: "Num_Value",
  Language: "English",
  
  CustomerName: "Customer name",
  Email: "email@gmail.com",
  
  RefNum: "0102",
  Code: "code",
  
  Country: "ES",
  Address: "Addr",
}

const fields = [
  {
    firstStep: [{ fieldName: 'Num' }, { fieldName: 'Language' }],
  },
  {
    secondStep: [{ fieldName: 'CustomerName' }, { fieldName: 'Email' }],
  },
  {
    thirdStep: [{ fieldName: 'RefNum' }, { fieldName: 'Code' }],
  },
  {
    fourthStep: [{ fieldName: 'Country' }, { fieldName: 'Address' }],
  }
];

const res = fields.reduce((item, acc) => {

  // How to map fields with values and get the expected result? 
  console.log(Object.entries(item), 'item');
  
  return acc;
}, []);


console.log(res, 'res');


// Expected result
const result = [
  {
    title: "firstStep",
    data: [{ fieldName: "Num", value: "Num_Value"}, { fieldName: "Language", value: "English"}]
  },
  {
    title: "secondStep",
    data: [{ fieldName: "CustomerName", value: "Customer name"}, { fieldName: "Email", value: "email@gmail.com"}]
  },
  {
    title: "thirdStep",
    data: [{ fieldName: "RefNum", value: "0102"}, { fieldName: "Code", value: "code"}]
  },
  {
    title: "fourthStep",
    data: [{ fieldName: "Country", value: "ES"}, { fieldName: "Address", value: "Addr"}]
  }
];

1 Answers

You need to parse the key-value pairs of each element, and use .map to fill out the values:

const values = {
  Num: "Num_Value",
  Language: "English",
  
  CustomerName: "Customer name",
  Email: "email@gmail.com",
  
  RefNum: "0102",
  Code: "code",
  
  Country: "ES",
  Address: "Addr",
}

const fields = [
  {
    firstStep: [{ fieldName: 'Num' }, { fieldName: 'Language' }],
  },
  {
    secondStep: [{ fieldName: 'CustomerName' }, { fieldName: 'Email' }],
  },
  {
    thirdStep: [{ fieldName: 'RefNum' }, { fieldName: 'Code' }],
  },
  {
    fourthStep: [{ fieldName: 'Country' }, { fieldName: 'Address' }],
  }
];

const res = fields.reduce((acc, item) => {
  const [title] = Object.keys(item);
  const [fieldElements] = Object.values(item);
  const data = fieldElements.map(e => ({...e, value: values[e.fieldName] }));
  acc.push({ title, data });
  return acc;
}, []);


console.log(res);

Related