1

i have this data, and i want to mapping this data without using lodash

let temp = [{
    "2020": 0,
    "2021": 0,
    "Series": "Check Qty Plunger Lub"
  },
  {
    "2020": 1,
    "2021": 4,
    "Series": "Cleaning 5MK"
  }
];

and i want to remapping the object like this

[
    2020 : {
        Series : 2020,
        Check Qty Plunger Lub : 0,
        Cleaning 5MK : 1,
    },
    2021 : {
        Series : 2021,
        Check Qty Plunger Lub : 0,
        Cleaning 5MK : 4,
    },
    etc ..
]

the key is using year, and inside the year object is have dynamic keys using temp.series, and value is following the temp object

example : Check qty plunger lub have 0 value on 2020, and 0 on 2021 so the object must

    2020 : {
        Series : 2020,
        Check Qty Plunger Lub : 0,
        ...
    },
1
  • The desired output is a syntax error Commented May 5, 2021 at 9:41

1 Answer 1

1

You could reduce the array.

const
    data = [{ 2020: 0, 2021: 0, Series: "Check Qty Plunger Lub" }, { 2020: 1, 2021: 4, Series: "Cleaning 5MK" }],
    result = data.reduce((r, { Series: key, ...rest }) => {
        Object.entries(rest).forEach(([Series, v]) => {
            r[Series] ??= { Series, [key]: 0 };
            r[Series][key] = v;
        });
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.