【发布时间】:2019-07-29 13:24:32
【问题描述】:
我正在尝试修改数组中的属性并在其下添加新元素。
数组取自 - https://jsonplaceholder.typicode.com/users
我的代码只是添加了一个新属性而不是修改它们
我尝试了以下代码(通过使用 axios)
const axios = require('axios');
const getData = async() => {
let {data: myData} = await axios.get('https://jsonplaceholder.typicode.com/users')
myData.forEach((e) => {
myData.push({
phone: {
"phoneNumber": e.phone,
"phoneType": ''
}
})
})
console.log(myData)
}
我想要得到 -
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone":{
"phoneNumber": "1-770-736-8031 x56442",
"phoneType": ''
},
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
但我得到了
[ { id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
address:
{ street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: [Object] },
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company:
{ name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets' } },
{ phoneNumber: '1-770-736-8031 x56442', phoneType: '' },
]
【问题讨论】:
-
为什么你有 两个
myData.forEach循环在这里开始? -
这是我忘记删除的代码的一部分。刚刚更正了,抱歉。
-
没有“json 数组”这样的东西。 JSON 是一种文本格式。一旦你从 axios 得到它,它只是一个数组。
-
myData是一个数组,不知道为什么您希望在您的forEach之后得到其他东西
标签: javascript arrays node.js