我有一个像这样的数组
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 title="male">this is male</button>
<button title="female">this is female</button>
当我点击其中一个时,我想将点击按钮的对象基础推送到另一个数组
$('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);
});
我得到了这样的输出
[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)
如何将其更改为此
(2) [{…}, {…}]
0:{name: "mariam", y: 512}
1:{name: "linda", y: 412}
length:2
__proto__:Array(0)
答案 0 :(得分:0)
如果另一个数组data
(在这种情况下)为空
您可以直接指定如下。
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>
如果另一个数组data
(在这种情况下)非空
您可以使用 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>