如何为同一个元素创建多个名称的JavaScript对象?

时间:2016-10-04 19:31:14

标签: javascript object

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

i

所以我想知道我是否需要更多列名称,如果我在现有LAST_NAME之后使用逗号添加它们,或者还有其他方法可以做到这一点?此外,我想稍后将我的对象与循环中的记录进行比较。这应该是这样的:

var columnStruct = {ColumnName:"LAST_NAME"}

2 个答案:

答案 0 :(得分:-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这个词在数组中。

有两种形式可以在数组中找到结果,

答案 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...