如果我有一个JS对象:

var foo = { 'bar' : 'baz' }

如果我知道foo有基本的键/值结构,但不知道键的名称,我怎么能得到它?为…在吗?$ . each () ?


当前回答

除了……没有别的办法了。在。如果你不想使用它(可能是因为在每次迭代中测试hasOwnProperty的效率很低?),那么使用一个不同的构造,例如kvp的数组:

[{ key: 'key', value: 'value'}, ...]

其他回答

要显示为字符串,只需使用:

console.log("they are: " + JSON.stringify(foo));

给你的一句话:

const OBJECT = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
};

const value = 'value2';

const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];

window.console.log(key); // = key2

美元。每个都是一个库结构,而对于…In是原生js,这应该更好

如果您正在使用AWS CloudFront函数,那么这将为您工作。

function handler(event) {
    var response = event.response;
    var headers = response.headers;
    if("x-amz-meta-csp-hash" in headers){ 
        hash=headers["x-amz-meta-csp-hash"].value;
        console.log('hash is ' + hash);
    }
}
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

参考MDN