[英]Adding index in each array element of javascript
I have an array like this 我有这样的数组
[2003, 5010, 4006, 5007, 2003, 5010]
I am using this instruction to extract specific column and it gives the above output 我正在使用此指令提取特定的列,它给出了上面的输出
// profiles is a multidimensional array
var pofileIds = profiles.map((el) => el.TargetProfileId)
Now i want an output like this 现在我想要这样的输出
[{ ids : 2003}, { ids : 5010 },{ ids : 4006 },{ ids : 5007 },{ ids : 2003 }]
Or this 或这个
ids=2003&ids=5010&ids=4006&ids=5007&ids=2003
I am working on existing project and can't change this. 我正在处理现有项目,无法更改。 I need to call asp.net services to return me the desired data.
我需要致电asp.net服务以向我返回所需的数据。 The application is working on web and i am working to convert it to mobile but i am bound to use same services for mobile as web.
该应用程序正在Web上运行,我正在努力将其转换为移动设备,但我一定会使用与Web相同的移动服务。
When i use (el) => ...
I get an error. 当我使用
(el) => ...
出现错误。 Try like this 这样尝试
var arr = [2003, 5010, 4006, 5007, 2003, 5010];
var profileIds = arr.map(function (elem) {
return { "ID": elem };
});
Try: 尝试:
profiles.map(el => ({ ids: el.TargetProfileId }))
From Understanding ECMAScript 6 arrow functions : 通过了解ECMAScript 6箭头功能 :
Because curly braces are used to denote the function's body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses.
因为大括号用于表示函数的主体,所以要返回函数正文之外的对象文字的箭头函数必须将文字括在括号中。
Thanks for the answers you gave and for you time. 感谢您提供的答案和时间。 By the way i have found some simple solution for this which i am posting here.
顺便说一下,我已经找到了一些简单的解决方案,我在这里发布。
Here is my array 这是我的数组
[2003, 5010, 4006, 5007, 2003, 5010]
First i used this instruction from user jsonscript. 首先,我使用了来自用户jsonscript的指令。 But i had to modify it a little
但是我不得不修改一下
var pofileIds = profiles.map((el) => { return { "ids": el.TargetProfileId }})
This produces this result 这产生了这个结果
[Object {ids=2003}, Object {ids=5010}, Object {ids=4006}, Object {ids=5007}, Object {ids=2003}, Object {ids=5010}]
Then using jquery $.param
然后使用jQuery
$.param
pofileIds = pofileIds.map((el) => $.param(el) )
Output 产量
["ids=2003", "ids=5010", "ids=4006", "ids=5007", "ids=2003", "ids=5010"]
And finally javascript join 最后javascript加入
pofileIds = pofileIds.join("&")
Output 产量
ids=2003&ids=5010&ids=4006&ids=5007&ids=2003&ids=5010
Hope it helps someone. 希望它可以帮助某人。
With pure JS should be very easy: 使用纯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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.