1

I want to store object property value inside the array .I have objects inside a object .I need to store skey property inside the array.But I tried like this

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/ It add dublicate item in array .

My expected outtput is this

**['ctr+d','ctr+m']**

2 Answers 2

1

You can use for...in loop to loop objects and if skey property exists inside current object push it into array

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)

You can also use Object.keys and 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)

Sign up to request clarification or add additional context in comments.

Comments

1

Just do

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) {
    var ob = obj[key];

    if(ob.hasOwnProperty('skey')){
      newArray.push(ob.skey)
    }
}

console.log(newArray)

or if you want to keep the same logic :

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(prop === 'skey'){
          newArray.push(ob['skey'])
        }

     }
}

console.log(newArray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.