2016-10-04 92 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... 
相關問題