gpt4 book ai didi

javascript - 将 Observable 数组转换为嵌套 JSON

转载 作者:行者123 更新时间:2023-12-03 09:29:52 27 4
gpt4 key购买 nike

我在获取正确存储为 JSON 的信息数组时遇到问题。

我做了一个fiddle to illustrate the problem 。输入一组标签并查看控制台以查看输出。

更多说明:

所以我有一个输入,它接受以逗号分隔的标签列表,然后对其进行格式化。

function createTagArray() {
// given an input value of 'tag1, tag2, tag3'
// returns array = ['tag1', 'tag2', 'tag3']
}

我认为接下来我需要做的是:循环数组并为每个项目创建一个“标签”对象,其中还包括标签的 id 以及与标签关联的联系人的 id。

每个对象都被推送到tags,一个可观察的数组。

function single_tag(id, contactId, tagLabel) {
var self = this;

self.id = id;
self.contactId = contactId;
self.tagLabel = tagLabel;
}

function createTags() {
var array = createTagArray();

for (var i = 0; i < array.length; i++) {
self.tags().push(new single_tag(uuid.generate(), self.contactId, array[i]));
}
}

然后,我将其转换为 JSON

self.contactInformation = function() {
return ko.toJS({
"id": self.contactId,
"firstname": self.firstname(),
"lastname": self.lastname(),
... other fields ...
"tags": self.tags(),
})
}

但是,当我检查调用此函数的控制台输出时,标签是数组的集合,而不是一个漂亮的 json 对象。

Messed up tags JSON

如何使其格式正确?

我试过this suggestion ,并且标签 json 的结构正确,但它是用转义引号存储的,因此这似乎是错误的。

感谢您的帮助!

最佳答案

我会推荐您使用KO的knockout.mapping插件,它允许将复杂的JSON结构映射到 View 模型,即使没有声明。

来自documentation

Let’s say you have a JavaScript object that looks like this:

var data = {
name: 'Scot',
children: [
{ id : 1, name : 'Alicw' }
]
}

You can map this to a view model without any problems:

var viewModel = ko.mapping.fromJS(data);

Now, let’s say the data is updated to be without any typos:

var data = {
name: 'Scott',
children: [
{ id : 1, name : 'Alice' }
]
}

Two things have happened here: name was changed from Scot to Scott and children[0].name was changed from Alicw to the typo-free Alice. You can update viewModel based on this new data:

ko.mapping.fromJS(data, viewModel);

And name would have changed as expected. However, in the children array, the child (Alicw) would have been completely removed and a new one (Alice) added. This is not completely what you would have expected. Instead, you would have expected that only the name property of the child was updated from Alicw to Alice, not that the entire child was replaced!

...

To solve this, you can specify which key the mapping plugin should use to determine if an object is new or old. You would set it up like this:

var mapping = {
'children': {
key: function(data) {
return ko.utils.unwrapObservable(data.id);
}
}
}
var viewModel = ko.mapping.fromJS(data, mapping);

关于javascript - 将 Observable 数组转换为嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31549209/

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