[英]Printed key and values from a Javascript object is duplicated
I have a JSON object in the following format我有以下格式的 JSON 对象
var myarray = {
"2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"],
"2020-01-21": ["08:00 - 09:00"]
};
What I want to do is to print a list with the key following each value of the list.我想要做的是用列表的每个值后面的键打印一个列表。 Expected outcome is
预期结果是
2020-01-20 | 08:00 - 09:00
2020-01-20 | 09:00 - 10:00
2020-01-21 | 08:00 - 09:00
I try to do this with the following code, but I have an unexpected behaviour.我尝试使用以下代码执行此操作,但出现意外行为。
var entries = '';
$.each(myarray, function(key, value) {
for (var i = 0; i < value.length; i++) {
entries += entries + '<div>' + key + ' | ' + value[i] + '</div>';
}
});
$('#entries').html(entries);
Where the outcome is结果在哪里
2020-01-20 | 08:00 - 09:00
2020-01-20 | 08:00 - 09:00
2020-01-20 | 09:00 - 10:00
2020-01-20 | 08:00 - 09:00
2020-01-20 | 08:00 - 09:00
2020-01-20 | 09:00 - 10:00
2020-01-21 | 08:00 - 09:00
You can find a jsfiddle here with a reproducable example您可以在此处找到带有可重现示例的 jsfiddle
The following line inside the for cycle: for 循环中的以下行:
entries += entries + '<div>' + key + ' | ' + value[i] + '</div>';
should be:应该:
entries += '<div>' + key + ' | ' + value[i] + '</div>';
It's clearly a typo in writing the code, with the correction your fiddle example will give:这显然是编写代码时的一个错字,您的小提琴示例将给出更正:
2020-01-20 | 08:00 - 09:00
2020-01-20 | 09:00 - 10:00
2020-01-21 | 08:00 - 09:00
Hope it helps.希望能帮助到你。
Replace this line:替换这一行:
entries += entries + '<div>' + key + ' | ' + value[i] + '</div>';
With this:有了这个:
entries += '<div>' + key + ' | ' + value[i] + '</div>';
You actually print the entries twice.您实际上打印了两次条目。
This will work for you.这对你有用。
var entries = '';
$.each(myarray, function(key, value) {
for (var i = 0; i < value.length; i++) {
entries += '<div>' + key + ' | ' + value[i] + '</div>';
}
});
$('#entries').html(entries);
You could do like this你可以这样做
entries = entries + '<div>' + key + ' | ' + value[i] + '</div>'
or或者
entries += '<div>' + key + ' | ' + value[i] + '</div>'
You are using two types of addition assignment in a single line, which is why you are getting that output.您在一行中使用了两种类型的加法赋值,这就是您获得该输出的原因。 If you replace
+=
with =
or remove entries +
from that line, you will get your desired output.如果将
+=
替换为=
或从该行中删除entries +
,您将获得所需的输出。
The two possible corrections are below:两种可能的修正如下:
entries = entries + '<div>' + key + ' | ' + value[i] + '</div>';
and和
entries += '<div>' + key + ' | ' + value[i] + '</div>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.