如何根据键匹配获取对象

时间:2018-02-15 07:15:17

标签: javascript jquery

object找到array所有keys

array时遇到问题

我希望获得与key <{1}} var allUsers = ['ab','ac','dc']; var allData = [ { '_id':132323, 'ab':{ 'name':'abonly', 'age':34 }, }, { '_id':9993, 'dc':{ 'name':'dconly', 'age':34 }, }, ] for(var i=0;i<allUsers.length;i++){ var foundObject = allData.find(function(){ return allData.allUsers[i]; }); // do other operation console.log(foundObject); }匹配的所有对象

问题:如何根据键

获取对象

请提前帮助我!

&#13;
&#13;
'This is the code that runs when the users clicks the button
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'This is the code that copies the text in the text box to the list box
        ListBox1.Items.Add(TextBox1.Text)
        'This code clears the text in the text box
        TextBox1.Text = ""
    End Sub
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以使用hasOwnProperty()方法来实现此目标。

&#13;
&#13;
var allUsers = ['ab','ac','dc'];

var allData = [

    {

       '_id':132323,
       'ab':{
           'name':'abonly',
           'age':34
         },

    },
    
    
     {

       '_id':9993,
       'dc':{
           'name':'dconly',
           'age':34
         },

    },
]

allUsers.map(function(el) {  
	allData.map(function(datael) { 
		if(datael.hasOwnProperty(el))  {
			console.log(datael[el]);
		}
	})  
})	
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
var allUsers = ['ab','ac','dc'];

var allData = [

    {

       '_id':132323,
       'ab':{
           'name':'abonly',
           'age':34
         },

    },
    
    
     {

       '_id':9993,
       'dc':{
           'name':'dconly',
           'age':34
         },

    },
];

var matches = [];
var objects = [];

allData.forEach(function(v){
	if(allUsers.indexOf(Object.keys(v)[1]) != -1){
		matches.push(v);
    objects.push(v[Object.keys(v)[1]]);
	}
});

console.log(objects);
console.log(matches);
&#13;
&#13;
&#13;

这是普通JavaScript中的解决方案。

objects仅包含对象 matches包含与数组类似的元素。

答案 2 :(得分:0)

如果您正在寻找单个元素,请使用find,但是您希望所有这些元素都符合此条件,filter就是您应该使用的内容。如果您想要解释代码,请随时提问。

var allUsers = ['ab','ac','dc'];
let item1 = {'_id':132323, 'ab':{'name':'abonly','age':34}}
let item2 = {'_id':9993,'dc':{'name':'dconly','age':34}}
var allData = [item1, item2]
let foundObject = allData.filter(object => {
 let objKeys = Object.keys(object)
 return objKeys.find(key => allUsers.includes(key))
})
   
console.log(foundObject)