Javascript javascript动态填充关联数组并获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6886858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript dynamically populate associative array and get values
提问by Nomad
I want to build an associative array based on an array and then get the values of that associative array. The structure of the associative array is as follows:
我想基于数组构建一个关联数组,然后获取该关联数组的值。关联数组的结构如下:
var myAssociativeArr = new Array();
myAssociativeArr = [
{ id:'1',
lname:'doe',
fname:'john'
},
{ id:'2',
lname:'smith',
fname:'john'
}
]
I have three arrays of the same length from which I will build this associative array i.e. id, lname and fname array.
我有三个长度相同的数组,我将从中构建这个关联数组,即 id、lname 和 fname 数组。
for(var i=0; idArray.length;i++)
{
myAssociativeArr [id]=idArray[i];
myAssociativeArr [lname]=lnameArray[i];
myAssociativeArr [fname]=fnameArray[i];
}
Please tell me if the above approach is correct, if not how can I build this array and also how can I get the values of this array via a loop.
请告诉我上述方法是否正确,如果不正确,我该如何构建这个数组,以及如何通过循环获取这个数组的值。
Your help will be appreciated.
您的帮助将不胜感激。
回答by Jeremy Roman
You are very close. First of all, if you wish to use the array subscript notation, you have to pass the keys themselves (strings in your case, like this):
你很亲近。首先,如果你想使用数组下标符号,你必须传递键本身(在你的情况下是字符串,像这样):
var myAssociativeArr = [];
for (var i=0; i < idArray.length; i++) {
var newElement = {};
newElement['id'] = idArray[i];
newElement['lname'] = lnameArray[i];
newElement['fname'] = fnameArray[i];
myAssociativeArr.push(newElement);
}
Where the key names are known strings, it's often preferable to use the completely equivalent notation of object properties:
当键名是已知字符串时,通常最好使用完全等效的对象属性表示法:
var myAssociativeArr = [];
for (var i=0; i < idArray.length; i++) {
var newElement = {};
newElement.id = idArray[i];
newElement.lname = lnameArray[i];
newElement.fname = fnameArray[i];
myAssociativeArr.push(newElement);
}
You can be even more concise by using object literals, as you did in your sample output:
通过使用对象字面量,您可以更加简洁,就像您在示例输出中所做的那样:
var myAssociativeArr = [];
for (var i=0; i < idArray.length; i++) {
myAssociativeArr.push({
id: idArray[i],
lname: lnameArray[i],
fname: fnameArray[i]
});
}
Edit: fixed loop indexing to not be infinite.
编辑:固定循环索引不是无限的。
You read elements the same way you write them: myAssociativeArr[i]['id']
etc., or myAssociativeArr[i].id
etc.
您以与编写元素相同的方式阅读元素:myAssociativeArr[i]['id']
等等,或myAssociativeArr[i].id
等等。
For lookups by ID, it's a good idea to construct an object for this.
对于按 ID 查找,最好为此构造一个对象。
var myObject = {};
for (var i=0; i < idArray.length; i++) {
myObject[idArray[i]] = {
id: idArray[i],
lname: lnameArray[i],
fname: fnameArray[i]
};
}
To look up:
去查查看:
myObject['2'] // => { id: '2', ... }
回答by Charles Ma
not quite, try this:
不完全是,试试这个:
for(var i=0; idArray.length; i++)
{
myAssociativeArr[i] = {
id: idArray[i],
lname: lnameArray[i],
fname: fnameArray[i]
};
}
to get the id of the 5th element: myAossociativeArr[i]['id']
, I'm sure you can figure out the rest from here ;)
获取第 5 个元素的 id: myAossociativeArr[i]['id']
,我相信你可以从这里找出其余的 ;)
回答by lovesh
for(var i=0; idArray.length;i++)
{
myAssociativeArr [i][id]=idArray[i];
myAssociativeArr [i][lname]=lnameArray[i];
myAssociativeArr [i][fname]=fnameArray[i];
}
回答by Patrick Assoa Adou
Fast-forward, eight years later, using ECMAScript 2015, we would solve this problem by doing:
快进,八年后,使用 ECMAScript 2015,我们将通过以下方式解决这个问题:
let assocArr = idArray
.map(x=>{ return {id: x}})
.map((x,index) => Object.assign({lname: lname[index]}, x))
.map((x,index) =>Object.assign({fname: fname[index]}, x) )
.reduce((assoc,obj) => {let target = {};target[obj.id] = obj; return Object.assign(target,assoc) }, {})
Or by using reduce only:
或者只使用reduce:
let assocArr = idArray.reduce((assoc, x, index) => {
let target = {};
target[x] = { id: x, lname: lname[index], fname: fname[index] };
return Object.assign(target, assoc);
}, {});
If it were ever needed, a more flexible function that does the kind of things above is:
如果需要的话,一个更灵活的函数可以做上面的事情:
function glue(properties) {
let propsArrays = Object.entries(properties);
let lookUp = properties[properties.lookUpKey];
let propertyArrays = propsArrays.filter(
([key, value]) => key !== "lookUpKey"
);
return propertyArrays.reduce(
(assoc, props, index) => {
let [key, values] = [...props];
return values.reduce((assoc, prop, j) => {
let target = {};
target[key] = prop;
assoc[lookUp[j]] = Object.assign(target, assoc[lookUp[j]]);
return assoc;
}, assoc);
},
lookUp.reduce((assoc, id) => {
assoc[id] = {};
return assoc;
}, {})
);
}
You give it an object such as
你给它一个对象,比如
var properties = {id: idArray, lname: lname, fname: fname, lookUpKey: 'id'}
And based on the object's property names as well as the lookup array key, and it will glue those properties together as objects in an array. The function turns the properties object into an array of key/value pairs with:
并且基于对象的属性名称以及查找数组键,它将这些属性粘合在一起作为数组中的对象。该函数将属性对象转换为键/值对数组,其中包含:
let propsArrays = Object.entries(properties);
Then it extracts the lookUp keys and the actual properties to glue into their respective arrays:
然后它提取查找键和实际属性以粘合到它们各自的数组中:
let lookUp = properties[properties.lookUpKey];
let propertyArrays = propsArrays.filter(([key, value]) => key !== "lookUpKey");
Then, it uses nested reduce
s to process the properties into arrays of objects with the right properties. Note that:
然后,它使用嵌套的reduce
s 将属性处理为具有正确属性的对象数组。注意:
lookUp.reduce((assoc, id) => {
assoc[id] = {};
return assoc;
}, {})
initializes the outermost reduce
with an object with keys/properties that are the values in the lookup array. The values associated to those keys are just empty objects at the beginning. The innermost reduce
will then merge the appropriate properties into those objects by using:
reduce
使用键/属性作为查找数组中的值的对象初始化最外层。与这些键关联的值在开始时只是空对象。然后,最里面的reduce
将使用以下方法将适当的属性合并到这些对象中:
assoc[lookUp[j]] = Object.assign(target, assoc[lookUp[j]])