Skip to content
Advertisement

Best way to Filter and Map the combination of an array and an object [closed]

What is the best way to map this? I have an array of 5 stages here which is the initial stages array. However, I need to map the following newData array against these stages. field_4 should map against field-4. And field_5 should map against field-5. I have also attached how it should be returned. I realise this probably isn’t the proper use of StackOverflow as it’s more of a question, but I’ve been trying for a while with no luck. Any pointers in the right direction would be great.

const stages = [
            { key: 'field-one' },
            { key: 'field-two' },
            { key: 'field-three' },
            { key: 'field-four' },
            { key: 'field-five' },
        ]

const newData = {
                field_four: 9,
                field_five: 'D',
            }

// should get

const stages  =
            [
                { key: 'field-one' },
                { key: 'field-two' },
                { key: 'field-three' },
                { key: 'field-four', value: 'D' },
                { key: 'field-five', value: 9 },
            ];

Advertisement

Answer

Just run a simple map function, compare the properties. If the required property is found, then append that object with a new value

const stages = [
  { key: "bank-feeds" },
  { key: "has-property" },
  { key: "other-loans" },
  { key: "industry-code" },
  { key: "time-in-business" }
];

const newData = {
  trading_time_months: 9,
  industry_code: "D"
};

const result = stages.map((stage) => {
  const { key } = stage;
  if (key === "industry-code") {
     return { ...stage, value: newData.industry_code };
  } else if (key === "time-in-business") {
     return { ...stage, value: newData.trading_time_months };
  } else {
     return stage;
  }
});

console.log(result);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement