我有这种格式的JS数组,我想获取diff中的所有键。变量和diff变量中的值。这是我的代码,我试图在差异中获取键和值。变量。
<script>
var testVar = [ {ANUMBER: "new message"}, {ANUMBER: "new message number"}, {ANUMBER: "new message email "},{AMDL: "new message"}];
for (var labelkey in testVar){
if (errorsarr.hasOwnProperty(labelkey)) {
var val = errorsarr[labelkey];
//console.log(val);
console.log(labelkey);
}
}
</script>
答案 0 :(得分:0)
使用Object.entries()函数,您可以获得key
,value
对数组,可以通过for ... of
循环进行循环。
var testVar = {1: "first", 2: "second", 3: "third"}
for (let [key, value] of Object.entries(testVar)){
console.log(key, value)
}
答案 1 :(得分:0)
首先,您需要两个循环来访问数组对象的每个键,因为testVar
是一个数组。第一个循环遍历数组,第二个循环遍历对象。
var testVar = [ {ANUMBER: "new message"}, {ANUMBER: "new message number"}, {ANUMBER: "new message email "},{ANUMBER: "new message"}];
JSON.stringify(testVar);
for( labelkey in testVar){
var value= testVar[labelkey];
for( key in value ){
console.log("Key="+key, "and value="+value[key]);
}
}
答案 2 :(得分:0)
您可以遍历每个元素,并使用Object.entries
获取每个对象的键和值。
var testVar = [{ 1: "new message" }, { 2: "new message number" }, { 3: "new message email " }, { 4: "new message" }];
var keys = [];
var values = [];
testVar.forEach(e => {
var [key, value] = Object.entries(e)[0];
keys.push(key) && values.push(value)
});
console.log(keys)
console.log(values)
OR
var testVar = [{ 1: "new message" }, { 2: "new message number" }, { 3: "new message email " }, { 4: "new message" }];
var keys = testVar.map(e => Object.entries(e)[0][0]);
var values = testVar.map(e => Object.entries(e)[0][1]);
console.log(keys)
console.log(values)
答案 3 :(得分:0)
var testVar = [ {ANUMBER: "new message"}, {ANUMBER: "new message number"}, {ANUMBER: "new message email "},{AMDL: "new message"}];
ANUMBER_VALUE = [];
AMDL_VALUE = [];
for(var testvar of testVar){
for (let [key, value] of Object.entries(testvar)){
console.log("key: "+key)
console.log("value: "+value)
if(key == "ANUMBER"){
ANUMBER_VALUE.push(value);
}
else{
AMDL_VALUE.push(value);
}
}
}
console.log("ANUMBER_VALUE: "+ ANUMBER_VALUE)
console.log("AMDL_VALUE: "+ AMDL_VALUE)