gpt4 book ai didi

javascript - 如何将指定值放入相应位置

转载 作者:行者123 更新时间:2023-11-30 11:14:14 26 4
gpt4 key购买 nike

例如我有一串文字

"{"Date": 01/01/2019, "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}"

还有,我有一个实体

function demo(first, second) {
this.first = first,
this.second = second
}

是否可以将文本字符串转换为实体?例如,

"Date" 转到 first

01/01/2019 转到 second


"0" 转到第一个

“John” 获得第二名

最佳答案

您可以创建自己的,然后在您的json 对象上迭代创建对象

class CustomObject {
constructor(x, y) {
this.first = x;

this.second = y;
}
}

// your initial data as a json into a string
const str = '{"Date": "01/01/2019", "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}';

// transform your string into a json object
const json = JSON.parse(str);

// Build the custom objects, using the data inside of the json object
// The notation [x, y] is called -> destructuring
const objs = Object.entries(json).map(([x, y]) => new CustomObject(x, y));

// Now that we have the objects, display the values stored inside
// each one of them, to show they are correctly settled
objs.forEach(x => console.log(x.first, x.second));

关于javascript - 如何将指定值放入相应位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52298633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com