1

i have a object that looks like below sample object

{
    "op1": {
        "color": [
            "red",
            "yellow"
        ],
        "size":[
            1,3
        ]
    },
    "op2": {
        "color": [
            "black",
            "green"
        ],
        "size":[
            1,2
        ]
    },
    "op3": {
        "color": [
            "black"
        ]
    }
}

then i need to aggregate all key's values into one key like this note: properties will be dynamic

{
    "all": {
        "color": [
            "red",
            "yellow",
            "black",
            "green"
        ],
        "size": [
            1,
            2,
            3
        ]
    }
}

i tired lodash merge but merge works on parent level

2
  • Is the properties has fixed name color and size, or they have dynamic name and level? Commented Oct 20, 2022 at 10:32
  • no properties will be dynamic Commented Oct 20, 2022 at 10:38

1 Answer 1

1

Get the object's values, and then spread into _.mergeWith().

In the customizer function _.mergeWith() check if the 1st value (a) is an array. If it is an array, use _.union() to get an array of unique value from both a and b. If it's not an array, return undefined, so the default _.merge() algorithm would be used to combine the items.

const { mergeWith, values, isArray, union } = _

const fn = obj => mergeWith({}, ...values(obj), (a, b) => 
  isArray(a) ? union(a, b) : undefined
)

const obj = {"op1":{"color":["red","yellow"],"size":[1,3]},"op2":{"color":["black","green"],"size":[1,2]},"op3":{"color":["black"]}}

const result = fn(obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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.