如何将对象检索到 Javascript 中的数组中?

How can I retrieve the object into an array in Javascript?

我目前正在练习 js 中的一些基本问题,并且对这些语言中的任何一种都相当陌生。如果另一个对象 "third" 具有相同的 属性 值,我想从对象 "second" 中将 属性 的值和名称检索到数组 "temp" 中。 当 属性 名称已经定义时,我可以做到这一点,但是如果我不知道实际的 属性 名称,我该如何做呢?可能正在使用 Object.keys()

我的代码是这样的:

      function where(second, third) {
  var arr = [];
  var temp=[];
  for(var i in second)
    {

      if(third.hasOwnProperty('last')){
        if(second[i].last===third.last){
          arr=second[i];
          temp.push(arr);
        }
      }
      if(third.hasOwnProperty('first')){
        if(second[i].first===third.first){
          arr=second[i];
          temp.push(arr);
        }
      }

    }
  return temp;
}

where([{ first: 'Ram', last: 'Ktm' }, { first: 'Sam', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });

结果数组是:[{ 'first': 'Tybalt', 'last': 'Capulet' }]

即使我不知道实际的 属性 名称,我如何才能检索到相同的结果。例如,这里的名字首尾可能是食物,用途未知。 我已经在这里处理了以下主题。

function where(second, third) {
  var tmp = [];
  var length = second.length;

  var i, k, test;
  // Go through second's each item to see that...
  for (i = 0; i < length; ++i) {
    test = second[i];
    // For all key in third that belongs to third (not inherited or else)
    for (k in third) {
      // Check has own property.
      if (!third.hasOwnProperty(k)) {
        continue;
      }
      // If second[i] don't have key `k` in second or second[i][k]'s value is 
      // not equal to third[k], then don't put it into tmp, start to check next.
      if (!third.hasOwnProperty(k)) {
        break;
      } else if (test[k] !== third[k]) {
        break;
      }
      tmp.push(test);
    }
  }
  return tmp;
}

我认为 getOwnPropertyName 就是您要查找的内容。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

Object.getOwnPropertyNames({a:1,2:"b",c:"a"}).sort() // returns Array [ "2", "a", "c" ]

我将扩展我的初始答案

var temp = [];

var myobj = [{cat:"Felix",dog:"Milo",bird:"Monkey",3:"pets"}, 
         {cat:"Wiskers",dog:"yapper",bird:"tweeter",1:"human"}];

var myobj2 = {cat:"Harry",dog:"Fuzz",1:"human"};

var objKeys = Object.getOwnPropertyNames(myobj); //will have key "1" that matches below

objKeys.forEach(function(key) {
    if(myobj2.hasOwnProperty(key)) {
        temp.push(myobj2[key]) // will push "human" to temp array
    }
})
function where(second, third) {
    var temp = [];
    var k = Object.keys(third)[0]; // expecting only one element!
    second.forEach(function (obj) {
        if (obj[k] === third[k]) {
            temp.push(obj);
        }
    });
    return temp;
}