我有一个对象数组。如果我做一个console.log,我可以看到这些对象数组。
[Object, Object, Object, Object,Object]
[0-4]
0:Object
Name: Nikhil
User_ID:123
admin:true
read:false
write:false
1:Object
Name:andy
User_ID:124
admin:false
read:true
write:false
2:Object
Name:Nik
User_ID:125
admin:false
read:false
write:true
3:Object
Name:ranea
User_ID:126
admin:false
read:false
write:true
4:Object
Name:isha
User_ID:127
admin:false
read:true
write:false
现在,如果我做JSON.stringify,我得到这个输出。
[{"Name":"Nikhil","User_ID":"123","admin":true,"read":false,"write":false},
{"Name":"andy","User_ID":"124","admin":false,"read":true,"write":false},
{"Name":"Nik","User_ID":"125","admin":false,"read":false,"write":true},
{"Name":"ranea","User_ID":"126","admin":false,"read":false,"write":true},
{"Name":"isha","User_ID":"127","admin":false,"read":true,"write":false}]
我没有对所有参数进行字符串化,而是只想做很少的事情。对于例如我不想传递姓名。我只想传递User_ID,因为它是唯一的,以及admin,read,write属性。
如何使用loadash创建新的对象数组,然后对结果进行字符串化。我在JSON.stringify之后的最终输出应该是这样的
[{"User_ID":"123","admin":true,"read":false,"write":false},
{"User_ID":"124","admin":false,"read":true,"write":false},
{"User_ID":"125","admin":false,"read":false,"write":true},
{"User_ID":"126","admin":false,"read":false,"write":true},
{"User_ID":"127","admin":false,"read":true,"write":false}]
答案 0 :(得分:3)
使用Libre Office documentation应该是:
var newArr = _.map(oldArray,
function(item) {
return _.pick(item, ['User_ID', 'admin', 'read', 'write']);
});
答案 1 :(得分:2)
您可以使用Array.map()功能。
var obj = [ { "Name": "Christophe", "Age": 42, "foo": "bar" }, { "Name": "Blah", "Age": 42, "foo": "foo2" }]
var filtered = obj.map(function (element) {
return {
"Name": element.Name
}
});
之后,filtered
包含您的对象,其中只包含您要保留的密钥,您可以JSON.stringify
。
console.log(JSON.stringify(filtered));
// [ {"Name": "Christophe"}, {"Name": "Blah"} ]
答案 2 :(得分:0)
您可以使用此小功能返回 新阵列。
var arr = [{
Name: "Nikhil",
User_ID: "123",
admin: "true",
read: "false",
write: "false"
}, {
Name: "andy",
User_ID: "124",
admin: "false",
read: "true",
write: "false"
}];
function returnArr(array) {
var arrNew = arr;
for (let in arrNew) {
delete arrNew[let].Name;
}
return JSON.stringify(arrNew);
}
document.write(returnArr(arr)); // or console.log(returnArr(arr))