infodev
infodev

Reputation: 5245

get some elements in Json array

I have a json array format

[
  {
    "code": "string",
    "codeB": "string",
    "country": "string",
    "industry": "string",
    "name": "string",
    "nameB": "string"
  }
]

I would create a new object with only some items:

[
  {
    "code": "string",
    "codeB": "string",
    "name": "string",
    "nameB": "string"
  }
]

I get data from localStorage then I do a filter on Items that I need

  var allData = JSON.parse(sessionStorage.getItem("groups"));
  var datafiltered = allData.filter(function(el) {
    return el.code && el.name && el.codeB && el.nameB;
  });
  console.log("data filtered", datafiltered);

Actually as a result I get empty array

Upvotes: 0

Views: 216

Answers (3)

Penny Liu
Penny Liu

Reputation: 17408

Here is an example using lodash _.pick function:

const test = [{
  "code": "string",
  "codeB": "string",
  "country": "string",
  "industry": "string",
  "name": "string",
  "nameB": "string"
}];

const keys = ['code', 'codeB', 'name', 'nameB'];

console.log(_.pick(test[0], keys));
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .map() to create a new Object Array

var datafiltered = allData.map(function (el) {
    return {
        code: el.code,
        name: el.name,
        codeB: el.codeB,
        nameB: el.nameB,
    }
});

var allData = [{
  "code": "string",
  "codeB": "string",
  "country": "string",
  "industry": "string",
  "name": "string",
  "nameB": "string"
}];

var datafiltered = allData.map(function(el) {
  return {
    code: el.code,
    name: el.name,
    codeB: el.codeB,
    nameB: el.nameB,
  }
});

console.log(datafiltered)

Upvotes: 6

Nina Scholz
Nina Scholz

Reputation: 386578

For getting some keys only, you could map these properties for a new object.

var data = [{ code: "string", codeB: "string", country: "string", industry: "string", name: "string", nameB: "string" }],
    keys = ['code', 'codeB', 'name', 'nameB'],
    result = data.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));

console.log(result);

Upvotes: 4

Related Questions