Javascript 附加 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51644166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:37:50  来源:igfitidea点击:

Javascript Append JSON Objects

javascriptarraysjson

提问by nil

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

如何在迭代for 循环时附加类似JSON 的结构

For Example (Pseudo Code):

例如(伪代码):

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

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

我的主要目标是附加尽可能多的组:日期和联系人作为 clients.length 数据保存。

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.

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

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

假设我只使用字符串:“日期”和“联系人”

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

    }
];

采纳答案by clucle

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)

回答by Chase

It's a simple push object to array operation. Please try below

这是一个简单的将对象推送到数组的操作。请尝试以下

var data=[];

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

回答by Wiliam Carvalho

(ES6)You can use map function to extract the data you wish, and then convert it to json.

(ES6)你可以使用map函数提取你想要的数据,然后将其转换为json。

let clients = [{date:"", contact:"", otherstuff:""}, {date:"", contact:"", otherstuff:""}]
let clientsMapped = clients.map(client => ({Date:client.date, Contact:client.contact}))
let yourJson = JSON.stringify(clientsMapped)