我有一个如下对象 -
var product = [{name:"laptop", price:"10000", avail:true},
{name:"keyboard", price:"500", avail: true},
{name:"bt mouse", price:"999", avail: false}];
这需要克隆到另一个具有有限属性的对象。
预期产量
onlyProduct = [{name:"laptop",avail:true},
{name:"keyboard",avail:true},
{name:"bt mouse",avail:false}];
我尝试使用extend克隆,但它提供了一个真正的副本
var onlyProduct = $.extend(true,{},product)
答案 0 :(得分:1)
此要求主要要求采用不同的方法:
var onlyProduct = []
// Loop through the main product array
$.each(product, function (i, n) {
// Push the required properties in the new onlyProduct array
onlyProduct.push({
name: n.name,
avail: n.avail
});
});
// View the new array in browser console
console.log(onlyProduct);
答案 1 :(得分:0)
var newProduct = [];
for (i in product){
newProduct[i] = {};
for (j in product[i]){
if(j != 'price'){
newProduct[i][j] = product[i][j];
}
}
}
DEMO JSFIDDLE检入控制台
答案 2 :(得分:0)
您也可以使用delete
var product = [{name:"laptop", price:"10000", avail:true},
{name:"keyboard", price:"500", avail: true},
{name:"bt mouse", price:"999", avail: false}];
var backup = product;
for (counter = 0; counter <product.length; counter++) {
delete product[counter]['price'];
}
console.log(product);