Home > Blockchain >  moving a key value pair out of an array
moving a key value pair out of an array

Time:07-16

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

this is the object

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

It should look like this

{
  "Name": "John",
  "Type": "DB",
  "Immediate_Action": "No",
}

What I have so far is this

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:

This code works for your example:

const { Results: results, ...rest } = {
  "Name": "John",
  "Results": [
    {
      "Type": "DB",
      "Immediate_Action": "No",
    }
  ]
}

const res = {...rest, ...results.reduce((prev, curr) => ({
  ...prev,
  ...curr
}), {})}

console.log(res)

But I don't know what you expect when the Results array has more than one element.

In that condition, if this code does not fill your needs, ask me to change it.

CodePudding user response:

however, it will join first Result with index 0, you can expand it

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

const mapOscarResults = (data) => {
for (let i in Object.keys(data)){
    if (Array.isArray(data[Object.keys(data)[i]])){
        newKey = data[Object.keys(data)[i]][0]
        data = {... data, ...newKey}
        delete data[Object.keys(data)[i]]
    }
}
return data
};

console.log(mapOscarResults(data))

CodePudding user response:

You can simply spread the Results array into an Object.assign() call (and then further spread the resulting object).

const input = { "Name": "John", "Results": [{ "Type": "DB", "Immediate_Action": "No", }, { "Another": "value"}] };

const { Results, ...rest } = input;
const refactored = { ...rest, ...Object.assign({}, ...Results) };

console.log(refactored)

  • Related