不确定我的标题是否描述了我想要正确执行的操作。基本上,我想要一个从包含对象的对象中提取属性的函数。我将需要循环遍历包含同一类的许多对象的各种数组并提取特定值。
myarray1[
0:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
}
1:
object2 = { same as object1 but with other property values }
];
myarray2[
0: { different type of object with a different set of nested properties that the function can extract }
1: { idem }
];
function extractProperty(objectArray, property) {
//How do I write this code?
propertyvalue = objectArray.property;
return propertyvalue;
}
extractProperty(myarray1[0], object.objectProp3) = "Seeya"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop1) = "Hello"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop3.objectProp1Prop3Prop1) = "Come here"
在最终代码中,函数需要能够遍历所有数组键并创建一个数组列表,其中包含原始数组中每个对象的所选属性,但我可以管理。这是需要从数组中的对象中提取的特定属性的发送到我不知道该怎么做的函数。
是否有一种通用的方法将属性的“路径”发送到函数中然后在那里使用它?怎么样?
感谢您的帮助!
答案 0 :(得分:-1)
您可以尝试递归:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
};
object2 = {
objectProp1: 'test1',
objectProp2: 'test2'
}
var myArray = [object1, object2];
function getProp(objArray, prop) {
for(var key in objArray) {
if (key == prop)
return objArray[key];
if (typeof objArray[key] == 'object')
return getProp(objArray[key], prop);
}
}
//test
document.getElementsByTagName('h1')[0].innerHTML = getProp(myArray[0],'objectProp1Prop3Prop1');
我为你添加了一个小提琴:https://jsfiddle.net/afabbro/vrVAP/
答案 1 :(得分:-1)
看起来像是对我的任务。所以我不会给你代码,但会解释这个方法。
try {
taxonDao.openCurrentSession();
List<Object[]> taxonList = taxonDao.list(parent, classificationId, taxonIds, expand_taxon);
List res = new ArrayList();
Map<String, Object> m1 = new HashMap<String, Object>();
TaxonUI ui = new TaxonUI();
Map<Long, Map<String, Object>> m2 = new HashMap<Long, Map<String, Object>>();
for (Object[] t : taxonList) {
Map<String, Object> m = new HashMap<String, Object>();
ui.setId((Long) t[0]);
ui.setTaxonid((Long) t[0]);
ui.setClassification((Long) t[4]);
ui.setPath((String) t[3]);
ui.setText((String) t[1]);
ui.setRank((Integer) t[2]);
if(t[5]!=null){
ui.setParent((Long)t[5]);
}
m.put("id", ui.getId());
m.put("taxonid", ui.getId());
m.put("text", ui.getText());
m.put("rank", ui.getRank());
m.put("path", ui.getPath());
m.put("classification", ui.getClassification());
m.put("parent", ui.getParent());
res.add(m);
}
return res;
} catch (Exception e) {
throw e;
} finally {
taxonDao.closeCurrentSession();
}
注意:您需要在两者之间添加一些验证。我已经跳过那些让你去探索;)