Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best functional-style syntax to build this object?

The below code achieves desired output. Is there a more elegant way to do this?

For example, is there some native javascript function like flatMap etc that would help?

(I know I could get rid of the intermediate variable pieces).

const config = {
    fieldName1: {
        validation: "schema1",
        value: "abcvalue here"
    },
    fieldName2: {
        validation: "schema2",
        value: "abcvalue here"
    },
}

// Desired output: 
// {
//     fieldName1: "schema1",
//     fieldName2: "schema2",
//     ...
// }
const extractValidation = (config) => {
    const pieces = Object.entries(config).map(
        ([key, val]) => ({
            [key]: val.validation
        })
    )
    return Object.assign({}, ...pieces)
}


extractValidation(config)
like image 500
defraggled Avatar asked Oct 28 '25 07:10

defraggled


1 Answers

It's more concise, and I think prettier, to pair fromEntries with a map over .entries.

const config = {
    fieldName1: {
        validation: "schema1",
        value: "abcvalue here"
    },
    fieldName2: {
        validation: "schema2",
        value: "abcvalue here"
    },
}

const extractValidation = (config) => Object.fromEntries(
  Object.entries(config).map(([k,v]) => [k, v.validation])
);

console.log(extractValidation(config))
like image 125
danh Avatar answered Oct 31 '25 01:10

danh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!