如何在不更改属性数据类型的情况下推送对象数组

How can I push an array of objects, without changing the data type of the property?

本文关键字:情况下 情况 下推 数组 对象 数据类型 属性      更新时间:2023-09-26
function where(collection, source) {
 var arr = [];
 for (var p in collection) {
    for (var x in source) {
        if (collection[p].hasOwnProperty(x)) {
            if (collection[p][x] === source[x]) {
                arr.push(collection[p]);
                break;
            }
            }
        }
    }
for (var i in arr) {
    if (Object.keys(arr[i]).length < Object.keys(source).length) {
        delete arr[i];
    }
}
  return arr;
  }
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], {"a": 1, "b": 2 });

第一个循环中的 arr.push 将对象放入数组中,但更改属性,使它们不再是字符串 - 从"a":1 to a:1.我需要属性周围的引号完好无损。

在寻找解决方案时,我遇到了一些信息,其中将对象推送到数组中,它只是引用对象本身,而不是直接将其复制到数组中。

这里有人有什么想法吗?感谢您的帮助。

Javascript 对象接受字符串作为属性。

您可以通过在推送新对象后检查其类型来验证这一点。

Object.keys({ "a": 1, "b": 2 })
  .map(prop => typeof prop);
// ["string", "string"]

控制台显示它们时不带引号,因为已经暗示它们是字符串。

ES2015引入了计算属性作为替代方法,但它们的语法明显不同。

var str = 'a';
var obj = { [a]: 1 };

也许在将对象推送到数组之前创建一个新的对象文字?

像...

if (collection[p][x] === source[x]) {
  var foo = new Object;
  // for all keys and values of collection[p]
  foo[*collection[p] property as string*] = *collection[p] property value*
  ...
  arr.push(foo);
  break;
}