0

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?

1

1 Answer 1

1

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)
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.