从两个数组生成JSON
I have to arrays which are related.
我必须要有相关的数组。
shortArray = ["ID-111", "ID-222"]
longArray = ["ID-111 bis", "ID-222 bis"]
I created them like that because I needed unique IDs in previous steps and now I must use the same color for each pair in the chart I'm drawing them.
我这样创建它们是因为在前面的步骤中我需要唯一的id,现在我必须为我画的图中的每一对使用相同的颜色。
My aim is to generate a string with this form:
我的目标是用这种形式生成一个字符串:
{
"ID-111 bis" : chart.color("ID-111"),
"ID-222 bis" : chart.color("ID-222"),
...
}
I tried to do it like this:
我试着这样做:
const result = {}
for(const item of longArray) {
result[item]=[];
result[item].push({item : "chart.color(" + shortArray+ ")"});
}
Which gives me this wrong output:
这给了我一个错误的输出:
{
"ID-111 bis" :[{item: "chart.color(ID-111,ID-222)"}],
"ID-222 bis" :[{item: "chart.color(ID-111,ID-222)"}]
}
Any ideas what should I change?
我该改变什么?
LATER EDIT:
后来编辑:
I saw many answers which are pretty similar but there is a condition that must be respected:
我看到了许多非常相似的答案,但有一个条件必须得到尊重:
The second argument should not be in quotes.
第二个论点不应该用引号。
"ID-111 bis" : chart.color("ID-111")
- good
"ID-111之二":图表。颜色("ID-111") -很好
"ID-111 bis" : "chart.color("ID-111")"
- bad
:“id - 111 bis chart.color(id - 111)”-坏
5 个解决方案
#1
1
You need to use the item
's value instead of actualValue
which seems to be some static value and is not dependent on item
in your logic
您需要使用项的值,而不是实际值,后者似乎是一些静态值,并且不依赖于逻辑中的项
And every array item seems to be a new array, which is not what you are looking for
每个数组项都是一个新的数组,这不是你要找的
result[item] = {item : "chart.color(" + item.split(" ")[0] + ")"};
Even more precisely
更精确
var finalValue = {};
shortArray.forEach( function(s){
finalValue[s+" bis"] = chart.color(s); //assuming that chart.color is the function you want to invoke
})
更多相关文章
- 如何将图像(PNG)转换为2D数组(二进制图像)?
- JavaScript循环输入创建一个对象数组
- 有没有办法检查两个数组是否具有相同的元素?
- js中数组的使用方法
- 为什么我不能删除数组的元素?
- 如何在Javascript中从Json数组创建路径路径?
- JavaScript数组操作函数方法详解
- 数组多重排序
- ES6学习笔记二之数组的扩展