Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - How to reformat object using its property value as property key?

how can I assign object property value as property key?

I have a set of data:

const mydata = [
    {
      "id": 001,
      "value": "Value 1",
      "title": "Title 1"
    },
    {
      "id": 002,
      "value": [
        {
          "Name": "Name 1",
          "Age": "20"
        },
        {
          "Name": "Name 2",
          "Age": "30"
        },
      ],
      "title": "Title 2"
    },
]

I want to reformat it to become:

const mydata = [
    {
      "Title 1": "Value 1"
    },
    {
      "Title 2": [
        {
          "Name": "Name 1",
          "Age": "20"
        },
        {
          "Name": "Name 2",
          "Age": "30"
        },
      ]
    },
]

I have tried this code to achieve it:

mydata.map((dt: any) => {
  dt.title: dt.value
});

However, it seems not working.

Any idea how can I reformat it to the one I desire?

Thanks.

question from:https://stackoverflow.com/questions/65660364/how-to-reformat-object-using-its-property-value-as-property-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please use following code.

Reference URL How to use a variable for a key in a JavaScript object literal?

const mydata = [
    {
      "id": 001,
      "value": "Value 1",
      "title": "Title 1"
    },
    {
      "id": 002,
      "value": [
        {
          "Name": "Name 1",
          "Age": "20"
        },
        {
          "Name": "Name 2",
          "Age": "30"
        },
      ],
      "title": "Title 2"
    },
];

let reData = []; 
mydata.forEach((dt)=>{
  reData.push({[dt.title]: dt.value});
});
console.log(reData);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...