为什么数组存储重复值而迭代对象在对象内?

时间:2016-05-06 14:29:18

标签: javascript jquery

我想在数组中存储对象属性值。我在对象中有对象。我需要在数组中存储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']**

2 个答案:

答案 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.keysreduce

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);