打印具有数组的对象的数组索引

时间:2018-11-15 16:15:28

标签: javascript arrays

我需要打印对象的数组索引,其中一些对象具有数组。

我的数组是:

IF NOT EXISTS 
(
SELECT * FROM [__TARGETINST__].[__TARGETDB__].[dbo].[SysObjects] o 
INNER JOIN [__TARGETINST__].[__TARGETDB__].[dbo].[SysColumns] c 
ON o.ID = c.ID WHERE o.name ='newtable_CLIENT'
) 
Begin 

EXECUTE ('

CREATE TABLE [__TARGETDB__].[dbo].newtable_CLIENT
(
Employeeid UniqueIdentifier NOT NULL, 
Sequence bigint NOT NULL,
RUID UniqueIdentifier NOT NULL,
SYS_EffectiveDate datetime NOT NULL, 
SYS_ModifiedBy Nvarchar(50) NULL, 
SYS_ModifiedDate datetime NOT NULL,
SYS_RequestID UniqueIdentifier NULL, 
Primary Key (Employeeid, sequence), 
Foreign key (employeeid) references employee(employeeid)
)

') AT [__TARGETINST__]

end

到目前为止,我尝试了以下方法。但是"contents": [{ "title": "Book1", "type": "CHECKBOX" }, { "title": "Book2", "type": "CHECKBOX" "onSelection": [{ "title" : "Quantity", "type" : "TEXT" }] }] 每次迭代都打印-1。第二个对象中有一个数组。因此,console.log自然必须将索引打印为1。

console.log是一个以对象为内容的数组

datalist

2 个答案:

答案 0 :(得分:1)

您可以使用Array.isArraysome来检查对象的值是否为数组:

var contents = [{
    "title": "Book1",
    "type": "CHECKBOX"
  },
  {
    "title": "Book2",
    "type": "CHECKBOX",
    "onSelection": [{
      "title": "Quantity",
      "type": "TEXT"
    }, ]
  }
];

contents.forEach((c, index) => {
  if (Object.values(c).some(Array.isArray)) console.log(index);
});

答案 1 :(得分:0)

此函数是一个简单的函数,它遍历数组并检查元素是否具有onSelection属性。如果这样做,则返回该索引。 break用于仅返回与需求匹配的第一个元素。

function getIndexOfItemWithOnSelection(datalist) {

    let index;

    for (let itemIndex in datalist) {
        var item = datalist[itemIndex];
        if (item.onSelection) {
            index = itemIndex;
            break;
        }
    }

    return index;
}