[英]javascript - covert an array to key value pair
I am new to javascript and I am trying to covert the array into key value pair. 我是javascript的新手,我试图将数组转换为键值对。
var arrayA = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}...]
so the end result would look like var arrayB = {orange:1, banana:2}
所以最终结果看起来像
var arrayB = {orange:1, banana:2}
I feel like I might have to use loop within a loop first to split on ,
and then another one to split on :
, but that seems messy. 我觉得我可能必须首先在循环中使用循环才能拆分
,
然后再使用另一个循环拆分:
但这看起来很混乱。
Thanks. 谢谢。
Try the following loop: create a new object with the key name
and the value value
of each object in arrayA
尝试以下循环:使用键
name
和arrayA
中每个对象的值value
创建一个新对象
var arrayA = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}...]
var obj = {}
$.each(arrayA,function(i,v){
obj[v.name] = v.value;
});
https://jsfiddle.net/z8h6omo6/ https://jsfiddle.net/z8h6omo6/
or without jquery 或没有jquery
for(i in arrayA){
obj[arrayA[i].name] = arrayA[i].value;
};
One simple approach would be to simply loop through the length of the array, setting a new Object
property based on the index of the Array
during each pass. 一种简单的方法是简单地循环遍历数组的长度,在每次传递期间根据
Array
的索引设置新的Object
属性。
var arrayA = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}];
var objectA = {};
for (var i = 0; i < arrayA.length; i++) {
objectA[arrayA[i].name] = arrayA[i].value;
}
Then objectA
will have the following structure: 然后
objectA
将具有以下结构:
{
"orange": 1,
"banana": 2
}
When I have done my codes, there are already two answers. 当我完成我的代码时,已经有两个答案了。 But I don't want to give up, So I write this.
但我不想放弃,所以我写这个。
var arrayA = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}];
var arr={};
for(var i = arrayA.length -1; i>=0; i--){
arr[Object.values(arrayA[i])[0]]=Object.values(arrayA[i])[1];
}
console.log(arr);
It should work in next year, if it doesn't, then check it in the year after next year, etc. Good luck. 它应该在明年工作,如果没有,那么在明年之后的一年检查,等等。祝你好运。
Reduce seems like a good candidate as it will iterate in order and only vist own properties that exist: Reduce似乎是一个很好的候选者,因为它将按顺序迭代并且只能访问存在的属性:
var arrayA = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}]; var obj = arrayA.reduce(function(acc, obj) { acc[obj.name] = obj.value; return acc; },{}); document.write(JSON.stringify(obj))
I would suggest to use Array#forEach
and an object, because reduce returns always the same, and thit is no necessary, because only one property is added. 我建议使用
Array#forEach
和一个对象,因为reduce返回总是相同的,并且没有必要,因为只添加了一个属性。
var array = [{"name":"orange", "value":"1"}, {"name":"banana", "value":"2"}], object = {}; array.forEach(function(a) { object[a.name] = a.value; }); document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.