Home > Net >  Placing an array in a key-value pair in the the high-level object with multiple values
Placing an array in a key-value pair in the the high-level object with multiple values

Time:07-17

I am trying to move everything in the Array Results outside and into the original object

this is the object and the array Results can have multiple values

{
  "Name": "John",
  "Results": [
    {
      "Type": "DB",
      "Immediate_Action": "No",
    }, 
{
      "Type": "system",
      "Immediate_Action": "Yes",
    }
  ]
}

It should look like this

{
  "Name": "John",
  "Type": ["DB","system"]
  "Immediate_Action": ["No","Yes"]
}

What I have so far is this data will be populated not at once but will be looped until the entire object is completed. mapped[key] is probably wrong.

const mapOscarResults = ({ data }) => {
    return data.map(entry => {
        let mapped = {...entry};
        entry.Results.forEach(key => {
            let Type =  mapped[key.Type]

            if (mapped[key]) {
                mapped[key].push(entry.Results[key]);
            } else {
                mapped[key] = [entry.Results[key]];
            }
        });
        return mapped;
    });
};

CodePudding user response:

It's a good case for reduce. Just collect the values for Results keys in arrays...

const input = {
  "Name": "John",
  "Results": [{
      "Type": "DB",
      "Immediate_Action": "No",
    },
    {
      "Type": "system",
      "Immediate_Action": "Yes",
    }
  ]
}

let output = { Name: input.Name }
output.Results = input.Results.reduce((acc, el) => {
  let keys = Object.keys(el);
  keys.forEach(key => {
    if (!acc[key]) acc[key] = [];
    acc[key].push(el[key]);
  });
  return acc;
}, {});

console.log(output)

CodePudding user response:

This should do the trick

const data = {
  "Name": "John",
  "Results": [
    {
      "Type": "DB",
      "Immediate_Action": "No",
    }, 
    {
      "Type": "system",
      "Immediate_Action": "Yes",
    }
  ]
};

const transformData = data => {
  const newData = { Name: data.Name };
  newData.Type = [];
  newData.Immediate_Action = [];

  data.Results.forEach(({ Type, Immediate_Action }) => {
    newData.Type.push(Type);
    newData.Immediate_Action.push(Immediate_Action);
  });

  return newData;
}

const newData = transformData(data);
console.log(newData);

CodePudding user response:

Try using reduce and entries

const data = {
  "Name": "John",
  "Results": [{
      "Type": "DB",
      "Immediate_Action": "No",
    },
    {
      "Type": "system",
      "Immediate_Action": "Yes",
    }
  ]
};

const restructure = obj => {
  obj.Results = obj.Results.reduce((accumu, current) => {
    for (const [key, val] of Object.entries(current)) {
      accumu[key] = [...accumu[key] ?? '', val] ;
    }
    return accumu;
  }, {});
  return obj;
}

console.log(restructure(data));

  • Related