通过名称将对象的属性拉入另一个对象

时间:2017-06-03 13:33:53

标签: javascript json lodash

我正在VueJS做一个项目,我有一个数据数组,其中包含许多对象。

这些对象是从PHP后端提取的,由

等值组成

id:2123 名称:"名称值" 状态:"活跃" account_id:" 2KGGALS2353255"

想象一下,我想通过键名将它们拆分成一个类似的数组,但我希望有一个由两个子对象组成的父对象

[
    0: {
     core: {
       id: 2123
       name: "Name Value"
     },
     extra: {
       status: "active",
       account_id: "2KGGALS2353255" 
     }
]

问题是如何使用Javascript实现这一目标?我不想事先修改PHP中的数据,除非这是Javascript中非常缺乏的。 我可以使用VueJS和Lodash。

3 个答案:

答案 0 :(得分:0)

我一直在寻找lodash的pick()方法。

https://lodash.com/docs/4.17.4#pick

答案 1 :(得分:0)

这应该适用于您的目的

function separate(obj, keys) {
  let target = {}, rest = {};
  Object.keys(obj).forEach(function(key) {
    if (keys.includes(key)) {
      target[key] = obj[key];
    } else {
      rest[key] = obj[key];
    }
  });
  return { target: target, rest: rest };
}

let stuff = { 
  id: 2123,
  name: "Name Value",
  status: "active",
  account_id: "2KGGALS2353255" 
};

let separated = separate(stuff, ['id', 'name']);

console.log({
  core: separated.target,
  extra: separated.rest
});

答案 2 :(得分:0)

使用ES6的object destructuringobject rest spread提案(需要babel transform),您可以Array#map将数组放入所需格式的新对象数组中:< / p>

const arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

const result = arr.map(({ id, name, ...extra }) => ({
  core: {
    id,
    name
  },
  extra
}));

console.log(result);

你可以使用lodash的_.pick()来获取核心_.omit()来获得额外的

var arr = [{"id":1,"name":"Name1","status":"active","account_id":"2KGGALS2353255"},{"id":2,"name":"Name2","status":"active","account_id":"4ABCLS2353255"},{"id":3,"name":"Name3","status":"active","account_id":"6LMNALS2353255"}];

var result = arr.map(function(obj) {
  return {
    core: _.pick(obj, ['id', 'name']),
    extra: _.omit(obj, ['id', 'name'])
  };
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>