[英]Add objects from within JSON array into JavaScript array with keys remapped
I have the following json returned from an ajax request我从 ajax 请求返回了以下 json
[
{
"id": "1",
"task": "eat pizza",
"username": "all"
},
{
"id": "2",
"task": "drink soda",
"username": "all"
}
]
I am trying to add specific pieces of data from the json to an existing js array.我正在尝试将特定的数据从 json 添加到现有的 js 数组。
this.$todoData2 = [
{
'id': '5',
'text': 'Cheese',
'done': false
},
]
I need to add json key id and its matching value - example: "id": key,我需要添加 json 密钥 ID 及其匹配值 - 例如:“id”:key,
I need to add json key task as text with its matching value - example: "text": key我需要将 json 关键任务添加为具有匹配值的文本 - 例如:“text”:key
I need to add a "done": "false" to set so a final result would look like:我需要添加一个 "done": "false" 来设置,以便最终结果如下所示:
this.$todoData2 = [
{
"id": "1",
"text": "eat pizza",
'done': false
}
{
"id": "2",
"text": "drink soda",
'done': false
}
{
'id': '5',
'text': 'Cheese',
'done': false
},
]
I have no examples of what I have tried as I am not sure where to even begin with this.我没有我尝试过的例子,因为我不知道从哪里开始。 Keep in mind that json may contain a lot more results.请记住,json 可能包含更多结果。
Use .forEach()
to iterate over the 'updates' Array, while destructuring the key / value pairs you want to use使用.forEach()
迭代“更新”数组,同时解构要使用的键/值对
Create your object, then .push()
it to the Array创建你的对象,然后.push()
到数组
const $todoData2 = [ {'id': '5', 'text': 'Cheese', 'done': false}, ]; const update = [ {"id": "1", "task": "eat pizza", "username": "all"}, {"id": "2", "task": "drink soda", "username": "all"} ]; update.forEach(({id, task}) => { $todoData2.push({ 'id': id, 'text': task, 'done': false }); }); console.log($todoData2);
You can merge both arrays and then use map
.您可以合并两个数组,然后使用map
。
let arr = [ { "id": "1", "task": "eat pizza", "username": "all" }, { "id": "2", "task": "drink soda", "username": "all" } ] let todoData2 = [ { 'id': '5', 'text': 'Cheese', 'done': false }, ] todoData2 = todoData2.concat(arr).map( obj => ({ id:obj.id, text:obj.task || obj.text , done:false }) ); console.log(todoData2)
If the point here is to simply append and rename keys, it may by done as simple as that:如果这里的重点是简单地附加和重命名键,它可以像这样简单地完成:
const newItems = [{"id":"1","task":"eat pizza","username":"all"},{"id":"2","task":"drink soda","username":"all"}], existingItems = [{"id":"5","text":"Cheese","done":false}] existingItems.push(...newItems.map(({id,task:text}) => ({id,text,done:false}))) console.log(existingItems)
.as-console-wrapper{min-height:100%}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.