如何有条件地将Array转换为对象

时间:2017-12-04 13:42:24

标签: javascript

不仅仅是在javascript中从数组转换为对象,我想省略特定的字段并将它们转换为对象。

这是我的输入数据。

taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

]

此处预期输出

taggedOUtput = {
    0: {id:0, left:100, top:100, thumbSize:100},
    1: {id:1, left:150, top:150, thumbSize:100},
    2: {id:2, left:200, top:200, thumbSize:100},
}

我们如何有条件地将Array转换为对象

4 个答案:

答案 0 :(得分:2)

只需使用function SendDeleteToController(checkid){ $.ajax({ type: "PUT", url: '@Url.Action("PutCheck", "Admin")', contentType: "application/json; charset=utf-8", datatype: JSON, data: JSON.stringify({ methodParam: checkid }), success: function(result) { //your request will return the json object for use in your callback function //something like below, though I dont know what your JSON result looks like $('body').append(result.id); }, error: function(result) { alert("error " + result); }); }); 方法。

Object.assign

答案 1 :(得分:2)

您可以映射到每个元素以返回预期的属性...



var taggedItems = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

].map(e => {
  return {
   id:e.id,
   left:e.left,
   top:e.top,
   thumbSize:e.thumbSize
  }
});

//Second method to have only one object
var res = {}
var taggedItems2 = [
    {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
    {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
    {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},

].forEach((e,i) => {
  return res[i]=e
});



console.log(taggedItems);
console.log(res)




答案 2 :(得分:0)

您可以使用Array.prototype.reduce()。在每次迭代中,您将curr转换为新对象。

const taggedItems = [
  { id: 0, left: 100, top: 100, thumbSize: 100, image: 'b', url: 'y' },
  { id: 1, left: 150, top: 150, thumbSize: 100, image: 'd', url: 'x' },
  { id: 2, left: 200, top: 200, thumbSize: 100, image: 'f', url: 'w' },
]

const yourObject = taggedItems.reduce((prev, curr) => ({
  ...prev,
  [curr.id]: {
    id: curr.id,
    left: curr.left,
    top: curr.top,
    thumbSize: curr.thumbSize,
  }
}), {})

console.log(yourObject)

答案 3 :(得分:0)

您可以使用reduce和原始属性来创建新对象,如下所示:

const taggedItems = [
  {id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
  {id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
  {id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},
];

const newTaggedItems = taggedItems.reduce((prev, {id, left, top, thumbSize}) => ({
  ...prev,
  [id]: { id, left, top, thumbSize }
}), {});

console.log(newTaggedItems);