如何使用角度获取根据父母和孩子的钥匙

时间:2018-12-10 18:19:30

标签: javascript json

在这里,我有一个对象数组

[{
    "id": "company",
    "checked": true,
    "model": true,
    "maker": true,
    "country": true,
    "enterprise": true
  },
  {
    "id": "config",
    "checked": true,
    "ram": true,
    "processor": true,
    "hdd": true
  }
]

当我尝试在此处获取对象键时,应该是:

预期输出

["company", "checked", "model", "maker", "country", "enterprise"]

我得到的是:

["id", "checked", "model", "maker", "country", "enterprise"]

那么我如何获得ID和其余键的值?

4 个答案:

答案 0 :(得分:1)

尝试一下:

$('.criteria').find('option[id-criteria="1"]').val(1);

答案 1 :(得分:1)

映射条目,如果值是布尔值,则返回键,否则返回值

const all = [{
    "id": "company",
    "checked": true,
    "model": true,
    "maker": true,
    "country": true,
    "enterprise": true
  },
  {
    "id": "config",
    "checked": true,
    "ram": true,
    "processor": true,
    "hdd": true
  }
]

const data = all.map(props =>
  Object.entries(props).map(([key, value]) =>
    typeof value === "boolean" ? key : value
  )
);

console.log(data)

答案 2 :(得分:0)

尝试一下:

var jsonArr = [{
    "id": "company",
    "checked": true,
    "model": true,
    "maker": true,
    "country": true,
    "enterprise": true
  },
  {
    "id": "config",
    "checked": true,
    "ram": true,
    "processor": true,
    "hdd": true
  }
];

const result = jsonArr.map((item, index) => {
  const keys = Object.keys(item);
  keys[0] = item[keys[0]];
  return keys;
});

console.log(result);

我假设id将始终是数组对象中的第一个key

答案 3 :(得分:0)

var jsonArr = [{
    "id": "company",
    "checked": true,
    "model": true,
    "maker": true,
    "country": true,
    "enterprise": true
  },
  {
    "id": "config",
    "checked": true,
    "ram": true,
    "processor": true,
    "hdd": true
  }
];

const result = jsonArr.map((item, index) => {
  const keys = Object.keys(item);
  keys.filter((key, keyIndex) => {
      //console.log(key);
      if(key === "id") {
          keys[keyIndex] = item[key];
      }
  });
  
  return keys;
});

console.log(result);

这将帮助您在任何地方找到任何钥匙。