简体   繁体   中英

Convert array to object with similar key/value pairs

I have an array of values as follows

[
    {
      "factor": {
        "data": "f1",
        "val": [
          "val1"
        ]
      }
    },
    {
      "factor": {
        "data": "f2",
        "val": [
          "val2"
        ]
      }
    }
  ]

Is there a way to convert it to below format

{
    "keyvalue": {
        "factor": {
            "data": "f1",
            "val": ["val1"]
        },
        "factor": {
            "data": "f2",
            "val": ["val2"]
        }
    }
}

Standard array parsing to object doesn't work in this case given keys has to be unique

It's impossible. Every key in the object has to be unique. To understand this, imagine you have an object with two identical keys:

const obj = {
  "key": 1,
  "key": 2
}

But what you should receive when you use an expression like obj.key ? 1 or 2 ? It's nonsense.

You should rethink your object structure, maybe you need an array of objects?

{
  "keyvalue": {
    "factor": [
      {
        "data": "f1",
        "val": ["val1"]
      },
      {
        "data": "f2",
        "val": ["val2"]
      }
    ]
  }
}

What you can do is use the data field as a key given it's always unique.

Something like this :

{
    "factor": {
        "f1": ["val1"],
        "f2": ["val2"]
    }
}

Here's how you would proceed to transform the array to the key/value object :

let keyValue = {"factor": {}};
theArray.forEach((item) => {
    const key = item.factor.data;
    const value = item.factor.val;
    keyValue.factor[key] = value;
});

now the keyValue object is as described.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM