我想在数组中存储对象属性值。我在对象中有对象。我需要在数组中存储skey
属性。但是我试过这样的
var obj ={
aa:{
name:"test"
},
bb:{
name:"test",
skey:"ctr+d"
},
cc:{
name:"test",
skey:"ctr+m"
},
dd:{
name:"test"
}
}
var newArray=[]
for (var key in obj) {
// skip loop if the property is from prototype
var ob = obj[key];
for (var prop in ob) {
// skip loop if the property is from prototype
if(ob.hasOwnProperty('skey')){
newArray.push(ob.skey)
}
}
}
console.log(newArray)
https://jsfiddle.net/x4ra3yso/3/ 它在数组中添加了dublicate项。
我的预期输出是这个
**['ctr+d','ctr+m']**
答案 0 :(得分:1)
您可以使用for...in
循环来循环对象,如果当前对象中存在skey
属性,则将其推入数组
var obj = {
aa: {name: "test"},
bb: {name: "test",skey: "ctr+d"},
cc: {name: "test",skey: "ctr+m"},
dd: {name: "test"}
}, result = [];
for (var p in obj) {
if (obj[p].skey) result.push(obj[p].skey);
}
console.log(result)
您还可以使用Object.keys
和reduce
var obj = {
aa: {name: "test"},
bb: {name: "test",skey: "ctr+d"},
cc: {name: "test",skey: "ctr+m"},
dd: {name: "test"}
}
obj = Object.keys(obj).reduce(function(sum, el) {
if(obj[el].skey) sum = sum.concat(obj[el].skey);
return sum;
}, [])
console.log(obj)
答案 1 :(得分:1)
只做
$first_id = $this->db->insert_id();
或者如果你想保持相同的逻辑:
$last_id = $first_id + ($count-1);