Home > OS >  Map new object from an array of objects
Map new object from an array of objects

Time:08-17

The following code creates a new array of objects but using the reference.value2 name as the property key.

const reference = [
    { value1: "valueA", value2: "valueB" },
    { value1: "valueC", value2: "valueD" },
    { value1: "valueE", value2: "valueF" }
];
const input = [
    { valueA: 'some text'},
    { valueC: 'some more text'},
    { valueX: 'text to ignore'}, // valueX doesn't appear in reference so should be ignored
    { valueE: 'yet more text'}
];

const outputArray = reference.map(({ value1, value2 }) => {
  const found = input.find(obj => obj[value1]);
  return {
    [value2]: found[value1]
  };
});

console.log(outputArray)

The output looks like this:

[
    { valueB: 'some text'},
    { valueD: 'some other text'},
    { valueF: 'yet more text'}
]

This is working correctly, however I would like to change the input from an array of objects to just an object, like this?

const input = {
    valueA: 'some text',
    valueC: 'some more text',
    valueX: 'text to ignore', // valueX doesn't appear in reference so should be ignored
    valueE: 'yet more text'
}

How do I handle this to acheive the same output?

CodePudding user response:

You can try this:

const reference = [
    { value1: "valueA", value2: "valueB" },
    { value1: "valueC", value2: "valueD" },
    { value1: "valueE", value2: "valueF" }
];
const input = {
    valueA: 'some text',
    valueC: 'some more text',
    valueX: 'text to ignore', // valueX doesn't appear in reference so should be ignored
    valueE: 'yet more text'
}

const outputArray = reference.map(({ value1, value2 }) => {

    if (value1 in input) {
        return {
            [value2]: input[value1]
        };
    }
});

console.log(outputArray)
  • Related