[英]Function to create key-value pairs from two object properties
I'm parsing a 2 column CSV file with d3.csv. 我正在使用d3.csv解析2列CSV文件。 Is there an existing JS, jQuery, or D3 function to turn the result into key-value pairs? 是否存在现有的JS,jQuery或D3函数将结果转换为键值对?
Example CSV input: CSV输入示例:
Option Value
first_name Don
last_name Smith
Example d3.csv output from Chrome console: Chrome控制台的示例d3.csv输出:
{ option: "first_name", value: "Don" },
{ option: "last_name", value: "Smith" }
Below is the output I would like (I want to use the option as a key, and the value as a ... value): 以下是我想要的输出(我想将选项用作键,并将值用作...值):
[{ first_name: "don" }, { last_name: "Smith" }]
If there is no existing function I was going to code something that loops through the object, and uses "option" as the new key, and "value" as it's value. 如果没有现存的函数,我将编写一些遍历对象的代码,并使用“ option”作为新键,并使用“ value”作为它的值。 I assumed something like this has already been written. 我以为这样的东西已经写好了。
Is this what you mean? 你是这个意思吗?
function makeArrayWithOptionAsKey(oldDataArray) {
var newDataArray = [];
for (var i=0; i<oldDataArray.length; i++) {
var option = oldDataArray[i]['option'];
var value = oldDataArray[i]['value'];
newDataArray.push({ option: value });
}
return newDataArray;
}
If this is what you're looking for you could also use JQuery's map: 如果这是您要查找的内容,则还可以使用JQuery的地图:
var arrayWithObjectAsKey = $.map(myObjList, function (el, i) {
var newElement = {};
newElement[el['option']] = el['value'];
return newElement;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.