2016-10-04 53 views
-2

我想创建包含多个列名的对象。所以,我的对象,我现在只有一个列名:如何用同一个元素的多个名称创建JavaScript对象?

var columnStruct = {ColumnName:"LAST_NAME"} 

所以我想知道如果我想要更多的列名应我逗号将它们添加我的现有LAST_NAME后或有一些其他的方式来做到这一点?另外我想稍后将我的对象与循环中的记录进行比较。这应该是这样的:

for (var i = 0; i < columnNames.length; i++) { 
     if(columnNames[i] == columnStruct.ColumnName){ 
      console.log('Same'); 
     }else{ 
      console.log('Not The Same'); 
     } 
} 
+2

您可以创建它们的数组,看看是否存在于数组中的值。 – vlaz

+0

@vlaz你可以提供任何示例如何检查数组中是否存在元素? –

+0

在较新的浏览器中,“[”a“,”b“,”c“] .include(”b“)将返回true,或者 - 适用于任何大于IE8的内容:'[”a“,”b “,”c“]。indexOf(”b“)!= -1' – vlaz

回答

-1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

随着ES6你可以这样做:

var inventory = [ 
     {name: 'apples', quantity: 2}, 
     {name: 'bananas', quantity: 0}, 
     {name: 'cherries', quantity: 5} 
    ]; 

function findCherries(fruit) { 
    return fruit.name === 'cherries'; 
} 

console.log(inventory.find(findCherries)); 

或者

[1, 2, 3].includes(2);  // true 
[1, 2, 3].includes(4);  // false 
[1, 2, 3].includes(3, 3); // false 
[1, 2, 3].includes(3, -1); // true 
[1, 2, NaN].includes(NaN); // true 


var ri_names = ["LAST_NAME", "SECOND_NAME", "FIRT_NAME", "AGE"]; 
ri.names.includes("LAST_NAMES"); 

你也可以这样做:

var ri_names = ["LAST_NAME", "SECOND_NAME", "FIRT_NAME", "AGE"]; 
var a = ri_names.indexOf("LAST_NAME"); 
console.log(a) // 0 

返回该位置,则如果结果大于-1,则该单词处于数组中。

有两种形式找到导致阵列,

-2
//you can not add more than one object with the same name like below! 
var abc={object1:'somsthing',object1:'something else'}; 
//As you can see this wolud be a total duplicate! 
//instead,Arraylize the object elements like... 
var columnStruct = ["ColumnName:LAST_NAME","And more..."]; 
for(var i in columnStruct){ 
    if(columnStruct.hasOwnProperty(i)){ 
     var column=columnStruct[i].split(':');//NOw u have both the column name and its result in an array 

     //below check to see that it is the right column u are checking... 
     if(column[0].match('/\bColumnName\b/','ig')){ 

      //now compare this with the result u wanted to see if its the same... 
      if(column[1].match('whatever')){}//for a string value 
      //or 
      if(column[1]=='whatever'){ 

      }else{ 
       //do something 
      } 

     } 

    } 
} 

//Hope it helps... 
相关问题