【问题标题】:How to create JavaScript object with multiple names for the same element?如何为同一个元素创建具有多个名称的 JavaScript 对象?
【发布时间】:2016-10-04 19:31:13
【问题描述】:

我想创建包含多个列名的对象。所以我现在拥有的对象只有一个列名:

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');
      }
}   

【问题讨论】:

  • 你可以创建一个数组,看看你的值是否存在于数组中。
  • @vlaz 您能否提供任何示例如何检查数组中是否存在元素?
  • 在较新的浏览器中,["a", "b", "c"].includes("b") 将返回 true,或者 - 适用于任何大于 IE8 的浏览器:["a", "b", "c"].indexOf("b") != -1

标签: javascript object


【解决方案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...
    

    【讨论】:

      猜你喜欢
      • 2013-04-05
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      相关资源
      最近更新 更多