javascript - JavaScript将json添加到现有对象
问题描述
我正在努力使用 Vue.js 将 JSON 添加到现有对象中。所以我有一个计算一些变体的函数,它现在运行良好,但我需要更改它们以便为我的 Laravel 后端提供正确的数据。
所以这就是我的数组的样子(这个数组用于计算变量)
"attributes":[
{
"title":{
"text":"Size",
"value":"1"
},
"values":[
"Red",
"Green"
]
},
{
"title":{
"text":"Color",
"value":"2"
},
"values":[
"X",
"M"
]
}
]
我正在这样计算它们:
addVariant: function () {
const parts = this.form.attributes.map(attribute => attribute.values);
const combinations = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
this.form.variants = combinations;
},
输出如下:
"variants":[
[
"Red",
"X"
],
[
"Red",
"M"
],
[
"Green",
"X"
],
[
"Green",
"M"
]
]
所以这计算得很好,但这个变体需要看起来像这样:
"variants":[
{
"title": "Red/M",
"slug": "prooooo",
"options": [
{
"key": "Color",
"value": "Red"
},
{
"key": "Size",
"value": "M"
}
]
},
{
"title": "Red/X",
"slug": "prooooo",
"options": [
{
"key": "Color",
"value": "Red"
},
{
"key": "Size",
"value": "X"
}
]
}
如您所见,我有一个由 options.values 计算的标题字段,但真正的问题是如何使该 JSON 看起来像最后一个给定的 JSON。
关于如何做的任何想法?
解决方案
据我所见,创建最终输出的缺失值是数组的key
属性,我在对象属性下的第一个数组options
中看到了这些属性。attributes
text
title
您可以做的第一个更改是创建parts
变量:而不是attribute.values
直接返回,而是map
通过它们来保存attribute.title.text
。
同时,我们设置返回对象的键以匹配options
来自所需输出的对象。
const parts = this.form.attributes.map((attribute) =>
attribute.values.map((value) => {
// `options` objects have `value` and `key` properties
return { value, key: attribute.title.text };
})
);
combinations
代码保持不变。
然后,我们循环combinations
并创建新variants
数组
let variants = [];
for (const combination of combinations) {
variants.push({
// use template strings to create the new title
title: `${combination[0].value}/${combination[1].value}`,
slug: "...the value that you want",
// the "combination" variable already has the structure that you want for "options"
options: combination
});
}
最终代码将如下所示:
addVariant: function () {
const parts = this.form.attributes.map((attribute) =>
attribute.values.map((value) => {
return { value, key: attribute.title.text };
})
);
const combinations = parts.reduce((a, b) =>
a.reduce((r, v) => r.concat(b.map((w) => [].concat(v, w))), [])
);
let variants = [];
for (const combination of combinations) {
variants.push({
title: `${combination[0].value}/${combination[1].value}`,
slug: "...the value that you want",
options: combination,
});
}
this.variants = variants;
}
推荐阅读
- swiftui - SwiftUI 在图像周围生成不需要的空间
- flask - 当架构没有更改时,防止生成 alembic 自动迁移
- google-apps-script - 每天调用的服务次数过多:电子邮件
- delphi - 如何将 TImage 组件内的鼠标坐标正确发送到 Android Path.moveTo() 和 Path.lineTo() 方法?
- javascript - 在 R-Shiny 模块中更改 DT 分页中的 pageType
- menu - Typo3 中的 TMENU - 从上一级插入 url
- java - 在TestNG的单元测试中,使用mokito stub函数时总是报nullPointerException,我没有找到解决办法
- javascript - 停止对此的点击操作
- string - Powershell 将字符串转换为字节大小
- java - Java - 从文本文件中读取数字,并对它们进行排序使负数变为零