i have an array like this
var assets = [
{
"name": "male",
"type": [
{
name: "tommy",
y: 512,
},
{
name: "rian",
y: 812,
},
],
},
{
"name": "female",
"type": [
{
name: "mariam",
y: 512,
},
{
name: "linda",
y: 412,
},
],
}
];
and have a button with same title same as their object's name
<button title="male">this is male</button>
<button title="female">this is female</button>
when i click one of them i want to push the object base of the clicked button to another array
$('button').on('click',function(){
var attr= $(this).attr('title');
var obj = assets.find(function (obj) { return obj.name === attr; });
data =[];
data.push(obj.type);
console.log(data);
});
i got an output like this
[Array(2)]
0:Array(2)
0:{name: "mariam", y: 512}
1:{name: "linda", y: 412}
length:2
__proto__: Array(0)
length:1
__proto__: Array(0)
how to change it to become like this
(2) [{…}, {…}]
0:{name: "mariam", y: 512}
1:{name: "linda", y: 412}
length:2
__proto__:Array(0)
If another array data
(in this case) is empty
You can directly assign like below.
var assets=[{"name":"male","type":[{name:"tommy",y:512,},{name:"rian",y:812,},],},{"name":"female","type":[{name:"mariam",y:512,},{name:"linda",y:412,},],}] $('button').on('click',function(){ var attr= $(this).attr('title'); var obj = assets.find(function (obj) { return obj.name === attr; }); data =obj.type; console.log(data); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button title="male">this is male</button> <button title="female">this is female</button>
If another array data
(in this case) is non-empty
You can use Array.concat
.
var assets=[{"name":"male","type":[{name:"tommy",y:512,},{name:"rian",y:812,},],},{"name":"female","type":[{name:"mariam",y:512,},{name:"linda",y:412,},],}] $('button').on('click',function(){ var attr= $(this).attr('title'); var obj = assets.find(function (obj) { return obj.name === attr; }); data =[]; data=data.concat(obj.type); // use concat which will also work if data array is not empty console.log(data); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button title="male">this is male</button> <button title="female">this is female</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.