[英]Converting user input from prompts in javascript into an array and then pushing it onto an object
[英]pushing an object onto an array from an array of objects in JavaScript
我試圖做一個通過對象數組(第一個參數)查找並返回具有匹配的屬性和值對(第二個參數)的所有對象組成的數組的函數。 如果要將源對象的每個屬性和值對包含在返回的數組中,則該對象必須存在於集合的對象中。
例如,如果第一個參數是
[{
first: "Romeo",
last: "Montague"
}, {
first: "Mercutio",
last: null
}, {
first: "Tybalt",
last: "Capulet"
}]
,第二個參數是{ last: "Capulet" }
,那么您必須從數組中返回第三個對象(第一個參數),因為它包含屬性和值,該對象作為第二個參數傳遞。
到目前為止,這是我已經嘗試過的方法,但是我要么在新數組中什么都沒有得到,要么所有對象都沒有插入:
function where(collection, source) {
var arr = [];
// iterating through the properties in course
for (var name in source){
// if the name from source is found in collection
for (var i =0; i<collection.length; i++) {
if (collection[i].hasOwnProperty(name))
{
// push the object onto the array?????
arr.push(collection[i]);
console.log(collection[i]);
}
}
}
return arr;
}
where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
使用Array.prototype.filter和Array.prototype.every :
如果我理解正確,那么您想要這樣的事情;
var src = {last: "Capulet"};
var arr = [
{
first: "Romeo",
last: "Montague"
},
{
first: "Mercutio",
last: null
},
{
first: "Tybalt",
last: "Capulet"
}];
var newArr = arr.filter(function(item) {
if(Object.keys(src).every(function(k){
return src.hasOwnProperty(k) && item.hasOwnProperty(k) && src[k] === item[k]}))
{
return item;
}
});
console.log(newArr);
我有兩種可能的解決方案
范例:
var result = _.filter(array, {last: "Capulet"});
var arr = [ { first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]; var res = _.filter(arr, {last: "Capulet"}); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.js"></script>
如果您不想從頭開始編寫函數來滿足您的需求,那么UnderscoreJS可能會讓您大吃一驚。 查看下面的鏈接。
underscore.js庫中的_.where(list,properties)
var list = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }];
console.log(_.where(list, { last: "Capulet" })); // prints on console
// [{ first: "Tybalt", last: "Capulet" }]
你可以試試這個
function where(collection, source) {
for (var i = 0; i < collection.length; i++){
var found = true;
for (var name in source){
//If one of the property does not match, do not return the object
if (collection[i][name] != source[name]){ found = false; }
}
if (found) {
//If you want the object
return collection[i];
//If you want the object in an array
return [collection[i]];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.