在 javascript 的每个数组元素中添加索引

Adding index in each array element of javascript

本文关键字:添加 索引 数组元素 javascript      更新时间:2023-09-26

我有一个这样的数组

[2003, 5010, 4006, 5007, 2003, 5010]

我正在使用此指令提取特定列,它给出了上述输出

// profiles is a multidimensional array
var pofileIds   =   profiles.map((el) => el.TargetProfileId)

现在我想要这样的输出

[{ ids : 2003}, { ids : 5010 },{ ids : 4006 },{ ids : 5007 },{ ids : 2003 }]

或者这个

ids=2003&ids=5010&ids=4006&ids=5007&ids=2003

我正在处理现有项目,无法更改。我需要调用 asp.net 服务来返回所需的数据。该应用程序正在网络上运行,我正在努力将其转换为移动设备,但我必须使用与网络相同的移动服务。

当我使用(el) => ...时,我收到一个错误。像这样尝试

var arr = [2003, 5010, 4006, 5007, 2003, 5010];
var profileIds = arr.map(function (elem) {
    return { "ID": elem };
});

尝试:

profiles.map(el => ({ ids: el.TargetProfileId }))

从理解 ECMAScript 6 箭头函数:

由于大括号用于表示函数的主体,因此想要返回函数主体外部的对象文本的箭头函数必须将文本括在括号中。

感谢您给出的答案和时间。顺便说一下,我找到了一些简单的解决方案,我在这里发布

这是我的阵列

[2003, 5010, 4006, 5007, 2003, 5010]

首先,我使用了用户jsonscript的这条指令。但我不得不稍微修改一下

var pofileIds   =   profiles.map((el) => { return { "ids": el.TargetProfileId }})

这会产生这个结果

[Object {ids=2003}, Object {ids=5010}, Object {ids=4006}, Object {ids=5007}, Object {ids=2003}, Object {ids=5010}]

然后使用 jquery $.param

pofileIds   =   pofileIds.map((el) => $.param(el) )

输出

["ids=2003", "ids=5010", "ids=4006", "ids=5007", "ids=2003", "ids=5010"]

最后是javascript加入

pofileIds   =   pofileIds.join("&")

输出

ids=2003&ids=5010&ids=4006&ids=5007&ids=2003&ids=5010

希望它对某人有所帮助。

使用纯JS应该很容易:

var myArray= [2003, 5010, 4006, 5007, 2003, 5010],
myObject,
myResponse = [];
for (var index in myArray)
{
    myObject = new Object();
    myObject.ids = myArray[index];
    myResponse.push(myObject);
}
//Output in the console for double check
console.log (myResponse);