简体   繁体   English

用lodash转换带有对象的javascript数组

[英]Transform javascript array with objects with lodash

I'm wondering what the best way would be to transform my javascript array with objects. 我想知道最好的方法是用对象转换我的javascript数组。 I have tried making a fancy chain with lodash but I can't figure it out. 我曾尝试用lodash制作花式链,但我不知道。

I need to format the data this way because of the way the backend works. 由于后端的工作方式,我需要以这种方式格式化数据。

// from:
var something = [
  {
    name: 'foo',
    stuff: [
      {
        id: 1
      },
      {
        id: 2
      },
      {
        id: 3
      }
    ]
  },
  {
    name: 'bar',
    stuff: []
  },
  {
    name: 'baz',
    stuff: [
      {
        id: 7
      },
      {
        id: 8
      }
    ]
  }
];

// to:
var transformed = [
  {
    name: 'foo',
    included: {
      included: [1, 2, 3]
    }
  },
  {
    name: 'bar',
    included: {
      included: []
    }
  },
  {
    name: 'baz',
    included: {
      included: [7, 8]
    }
  }
];

You can do this quite concisely with two map calls (the array built in or lodash's map), one nested to handle the "included" array within each object: 您可以使用两个map调用(内置数组或lodash的映射)非常简洁地完成此操作,一个嵌套以处理每个对象中的"included"数组:

const transformed = something.map(it => {
  return {
    name: it.name,
    included: {
      included: it.stuff.map(thing => thing.id)
    }
  };
});

No need for lodash , just use the Array.prototype.map function : 不需要lodash ,只需使用Array.prototype.map函数

// Sorry no fancy ES6 => here :S
var res = something.map(function(item) {
  item.included = {included : item.stuff.map(function(i) {return i.id})}
  delete(item.stuff)
  return item
})

Per @ssube 's comment: Per @ssube的评论:

var res = something.map(function(item) {
  return {
    included : {included : item.stuff.map(function(i) {return i.id})},
    name: item.name
  }
})

See this fiddle 看到这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM