Javascript附加JSON对象 [英] Javascript Append JSON Objects

查看:47
本文介绍了Javascript附加JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在遍历 for循环时,如何添加类似于JSON的结构?

How can I append a JSON like structure while iterating through a for loop?

例如(伪代码):

var i;
for (i = 0; i < clients.length; i++) { 
    date = clients.date;
    contact = clients.contact;
}

我的主要目标是添加与client.length数据一样多的日期和联系人组.

My main goal is to append as many groups of: dates and contacts as the clients.length data holds.

我需要每次循环迭代才能在日期和联系人组的多个索引下面创建类似的内容.我的总体目标是通过for循环创建如下所示的数据结构.

I need each loop iteration to create something like below of multiple indexes of date and contact groups. My overall goal is to have a data structure like below created through my for loop.

假设我只是将字符串用于:"Date"& 联系人"

Assume im just using strings for: "Date" & "Contact"

 var data = [
    {
        "Date": "2015-02-03",
        "Contact": 1
    },
    {
        "Date": "2017-01-22",
        "Contact": 2

    }
];

推荐答案

var data = []

function Client(date, contact) {
      this.date = date
      this.contact = contact
}

clients = new Array();

for (i = 0; i < 4; i++) {
    clients.push(new Client("2018-08-0" + i, i))
}

for (i = 0; i < clients.length; i++) {
    var dict = {}
    dict['Date'] = clients[i].date
    dict['Contact'] = clients[i].contact
    data[i] = dict
}

console.log(data)

这篇关于Javascript附加JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆