Javascript JSON object reorder - javascript

I've got the following JSON:
var obj =
{
"workers": [
{
"TimeStamp": "2020-03-13T10:08",
"Status": "status1",
"Name": "one",
"Number": 19.9
},
{
"TimeStamp": "2019-07-19T06:01",
"Status": "status2",
"Name": "one",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Status": "status2",
"Name": "one",
"Number": 10.1
},
{
"TimeStamp": "2019-07-21T23:53",
"Status": "status2",
"Name": "two",
"Number": 16.3
},
{
"TimeStamp": "2019-11-21T05:14",
"Status": "status1",
"Name": "three",
"Number": 122.54
},
...
]
};
As you see there's just 2 different status possible: "status1" and "status2".
Names should be filtered to be shown just once, but combine the two different status.
The respective status should include the "TimeStamp" and "Number" in an array.
In the end it should look like this:
{
"workers": [
{
"Name":"one",
"status1": [
{
"TimeStamp":"2020-03-13T10:08",
"Number": 19.9
}
],
"status2": [
{
"TimeStamp":"2019-07-19T06:01",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Number": 10.1
},
]
},
{
"Name":"two",
"status1": [],
"status2": [
{
"TimeStamp":"2019-07-21T23:53",
"Number": 16.3
}
]
},
{
"Name":"three",
"status1": [
{
"TimeStamp":"2019-11-21T05:14",
"Number": 122.54
}
],
"status2": []
}
]
}
I tried out the following so far:
var writeObj = { 'workers': [] };
for (var i = 0; i < obj.workers.length; i++) {
if(!Object.values(writeObj.workers).includes(obj.workers[i].Name)) {
writeObj['workers'].push({ Name: obj.workers[i].Name, 'status1': [], 'status2': [] });
for (var j = 0; j < obj.workers.length; j++) {
if (obj.workers[j].Name === obj.workers[i].Name && obj.workers[j].Status === 'status1') {
writeObj['workers'][i]['status1'].push({ TimeStamp: obj.workers[j].TimeStamp, Number: obj.workers[j].Number });
} else if (obj.workers[j].Name === obj.workers[i].Name && obj.workers[j].Status === 'status2') {
writeObj['workers'][i]['status2'].push({ TimeStamp: obj.workers[j].TimeStamp, Number: obj.workers[j].Number });
}
}
}
}
I'm stuck and can't see the mistake...
Thanks for any help!

You can aggregate your data using array.reduce:
var obj =
{
"workers": [
{
"TimeStamp": "2020-03-13T10:08",
"Status": "status1",
"Name": "one",
"Number": 19.9
},
{
"TimeStamp": "2019-07-19T06:01",
"Status": "status2",
"Name": "one",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Status": "status2",
"Name": "one",
"Number": 10.1
},
{
"TimeStamp": "2019-07-21T23:53",
"Status": "status2",
"Name": "two",
"Number": 16.3
},
{
"TimeStamp": "2019-11-21T05:14",
"Status": "status1",
"Name": "three",
"Number": 122.54
}
]
};
let output = obj.workers.reduce((acc,cur) => {
let {Name, Status, ...rest} = cur;
let match = acc.find(x => x.Name === Name);
if(!match){
match = { Name: Name };
acc.push(match);
}
if(!match[Status]){
match[Status] = [];
}
match[Status].push(rest);
return acc;
}, []);
console.log({workers: output});

You can use Array#reduce. Group by the Name key according to your format, then take the grouped values as the result. Time complexity is O(n).
var obj = { "workers": [ { "TimeStamp": "2020-03-13T10:08", "Status": "status1", "Name": "one", "Number": 19.9 }, { "TimeStamp": "2019-07-19T06:01", "Status": "status2", "Name": "one", "Number": 9 }, { "TimeStamp": "2020-04-22T05:10", "Status": "status2", "Name": "one", "Number": 10.1 }, { "TimeStamp": "2019-07-21T23:53", "Status": "status2", "Name": "two", "Number": 16.3 }, { "TimeStamp": "2019-11-21T05:14", "Status": "status1", "Name": "three", "Number": 122.54 }, ] };
const grouped = Object.values(obj.workers.reduce((a, e) => {
if (!a[e.Name]) {
a[e.Name] = {Name: e.Name, status1: [], status2: []};
}
a[e.Name][e.Status].push({TimeStamp: e.TimeStamp, Number: e.Number});
return a;
}, {}));
console.log(grouped);

Related

Group array nested value with reduce

I need to group the array with a nested value type.Id. How to change the current groupby function to achieve this.
Current function will group using the productName or Price. Need to group using a nested value type.id
Any help would be greatly appreciated!
Group by function
static groupBy<T>(data: T[], key: string): T[] {
return <T[]>data.reduce((a, b) => {
(a[b[key]] = a[b[key]] || []).push(x);
return <T[]>a;
}, {});
}
sample value:
var sales = [
{
"productName": "AAA",
"type": {
"id": 1,
"name": "Soap"
},
"price": 90
},
{
"productName": "BBB",
"type": {
"id": 1,
"name": "Soap"
},
"price": 85
},
{
"productName": "CCC",
"type": {
"id": 1,
"name": "Soap"
},
"price": 55
},
{
"productName": "DDD",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 2
},
{
"productName": "EEE",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 5
}
]
Expected Result:
{1},
[
{
"productName": "AAA",
"type": {
"id": 1,
"name": "Soap"
},
"price": 90
},
{
"productName": "BBB",
"type": {
"id": 1,
"name": "Soap"
},
"price": 85
},
{
"productName": "CCC",
"type": {
"id": 1,
"name": "Soap"
},
"price": 55
}],
{2},[
{
"productName": "DDD",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 2
},
{
"productName": "EEE",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 5
}
]
Add an accessor function to use properties at any depth,
function groupBy<T>(data: T[], key: string): T[] {
const path: string[] = key.split('.');
const accessor = (obj: T) => path.reduce((x,y) => x[y], obj)
return <T[]>data.reduce((a, b) => {
const value = accessor(b).toString();
(a[value] = a[value] || []).push(b);
return <T[]>a;
}, {});
}
console.log(groupBy(sales, 'type.id'))
Runnable JS version
const sales = [
{
"productName": "AAA",
"type": {
"id": 1,
"name": "Soap"
},
"price": 90
},
{
"productName": "BBB",
"type": {
"id": 1,
"name": "Soap"
},
"price": 85
},
{
"productName": "CCC",
"type": {
"id": 1,
"name": "Soap"
},
"price": 55
},
{
"productName": "DDD",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 2
},
{
"productName": "EEE",
"type": {
"id": 2,
"name": "shampoo"
},
"price": 5
}
]
function groupBy(data, key) {
const path = key.split('.');
const accessor = (obj) => {
return path.reduce((x,y) => {
return x[y]
}, obj).toString();
}
return data.reduce((a, b) => {
const prop = accessor(b);
(a[prop] = a[prop] || []).push(b);
//a[prop] = a[prop] || [];
//a[prop].push(b);
return a;
}, {});
}
console.log(groupBy(sales, 'type.id'))

Parse Nested Level Json In javascript

Sample Input:
[
{
"id": "p1",
"top": 130,
"left": 298,
"Key": "test1",
"Next": "special"
},
{
"id": "p2",
"Key": "special",
"specialkey": [
{"key": "1", "value": "p3"},
{"key": "0", "value": "p4"},
{"key": "2", "value": "p5"}
],
"Next": "",
"RepeatText": "p8",
"RepeatTextNew": "p9",
},
{
"id": "p3",
"user": "aa",
"Key": "test3",
"Text": "hi"
},
{
"id": "p4",
"Key": "special",
"specialkey": [
{"key": "1", "value": "p6"},
{"key": "0", "value": "p7"}
]
},
{
"id": "p5",
"user": "aa",
"Key": "test5",
"Text": "hi"
},
{
"id": "p6",
"user": "aa",
"Key": "test6",
"Text": "hi"
},
{
"id": "p7",
"user": "aa",
"Key": "test7",
"Text": "hi"
},
{
"id": "p8",
"user": "aa",
"Key": "test8",
"Text": "hi"
},
{
"id": "p9",
"user": "aa",
"Key": "test9",
"Text": "hi"
}
]
Sample Output:
{
"test1": {
"id": "p1",
"top": 130,
"left": 298,
"Key": "test1",
"Next": {
"special": {
"id": "p2",
"Key": "special",
"Next": "",
"RepeatText": {
"p8": {
"id": "p8",
"user": "aa",
"Key": "test8",
"Text": "hi"
}
},
"RepeatTextNew": {
"p9": {
"id": "p9",
"user": "aa",
"Key": "test9",
"Text": "hi"
}
},
"specialkey": [
{
"key": "1",
"value": {
"id": "p3",
"user": "aa",
"Key": "test3",
"Text": "hi"
}
},
{
"key": "0",
"value": {
"id": "p4",
"Key": "special",
"specialkey": [
{
"key": "1",
"value": {
"id": "p6",
"user": "aa",
"Key": "test6",
"Text": "hi"
}
},
{
"key": "0",
"value": {
"id": "p7",
"user": "aa",
"Key": "test7",
"Text": "hi"
}
}
]
}
},
{
"key": "2",
"value": {
"id": "p5",
"user": "aa",
"Key": "test5",
"Text": "hi"
}
}
]
}
}
}
}
When the key is equal to special it can have a nested structure and for either we just need to match with the next key
With the below code, I am not able to achieve the expected output.
const processObject = ({ Next, ...rest }) => {
const result = { ...rest };
if (formatData.find((y) => y.Key == 'special')) {
const nextObject = formatData.find((y) => y.Key == 'special')
if (nextObject.specialkey) {
for (let i = 0; i < nextObject.specialkey.length; i++) {
let currentObject = formatData.find((y) => y.id === nextObject.specialkey[i].value)
nextObject.specialkey[i].value = currentObject
}
result.Next = {
[nextObject.Key]: processObject(nextObject),
};
}
}
if (Next) {
const nextObject = formatData.find((y) => y.id === Next);
result.Next = {
[nextObject.Key]: processObject(nextObject),
};
}
return result;
};
const response = {
[formatData[0].Key]: processObject(formatData[0]),
};
return response
Is this what you're after?
const input = [
{
"id": "p1", "top": 130, "left" :298, "Key": "test1",
// I've changed this from "special" to "p2"
"Next": "p2"
// rest of input is the same...
},{"id":"p2","Key":"special","specialkey":[{"key":"1","value":"p3"},{"key":"0","value":"p4"},{"key":"2","value":"p5"}],"Next":"","RepeatText": "p8","RepeatTextNew":"p9"},{"id":"p3","user":"aa","Key":"test3","Text":"hi"},{"id":"p4","Key":"special","specialkey":[{"key":"1","value":"p6"},{"key":"0","value":"p7"}]},{"id":"p5","user":"aa","Key":"test5","Text":"hi"},{"id":"p6","user":"aa","Key":"test6","Text":"hi"},{"id":"p7","user":"aa","Key":"test7","Text":"hi"},{"id":"p8","user":"aa","Key":"test8","Text":"hi"},{"id":"p9","user":"aa","Key":"test9","Text": "hi"}];
// Gets an object by its id
const getById = id => input.find(x => x.id === id);
const processObject = ({ Next, specialkey, RepeatText, RepeatTextNew, ...rest }) => {
let processedNext;
if (Next) {
const nextObject = getById(Next);
processedNext = { [nextObject.Key]: processObject(nextObject) };
}
return {
...rest,
// This spread syntax means we don't add the Next or
// specialkey property if it isn't present in the input
// object
...processedNext ? { Next: processedNext } : {},
...RepeatText
? { RepeatText: { [RepeatText]: processObject(getById(RepeatText)) } }
: {},
...RepeatTextNew
? { RepeatTextNew: { [RepeatTextNew]: processObject(getById(RepeatTextNew)) } }
: {},
...specialkey
? {
specialkey: specialkey.map(({ key, value }) => ({
key,
value: processObject(getById(value))
}))
}
: {}
};
}
console.log(processObject(input[0]));
In your code, you seem to be looking up objects by their id, so that's why I changed the first object input's Next from "special" (the Key of the p2 object) to "p2".

Reduce it array to an easier way to map

I'm developing an application and have added new items to my array: type and description.
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
I previously did this to reduce it down to an easier way to map it:
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"]
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
To show the data before I did
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I need to add the description element and type.name to the above. For example for description:
description: e["description"]
To display the elements as in the table:
ITEM
DESCRIPTION
TYPE
202001
202002
I1
item1
type1
100
200
I2
item3
type2
-
300
How do I add and show?
EDIT: console.log(items_dicc[item])
{202001: 100, 202002: 200, description: "item1", type: "type1"}
202001: 100
202002: 200
description: "item1"
type: "type1"
__proto__: Object
{202002: 300, description: "item3", type: "type2"}
202002: 300
description: "item3"
type: "type2"
__proto__: Object
You can add the description and type attribute inside the reduce method like this,
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"],
'description': e['description'],
'type': e.type?.name,
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
console.log(items);
To add the for description and name in the table,
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
<td>{items_dicc[item]?.description}</td>
<td>{items_dicc[item]?.type}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I have been seeing your question regarding these type of tables from yesterday. You have posted several questions with similar things. I suggest you to read some article and understand how JS array methods works instead of asking incremental questions in SO.
Asking in SO might solve your problems for now, but in the long run you will suffer as you don't seem to have a grip on how these things works.
you can simplify your solution like this.
const array = [{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
}
]
const result = array.map(item => {
return Object.keys(item).reduce((a, c) => {
if (c === "date") {
a[item[c].name] = item.price;
} else if (c !== "price" && c !== "id") {
a[c] = (typeof item[c] === "object") ? item[c].name : item[c];
}
return a;
}, {})
});
console.log(result);

Filter array present inside a array of objects without affecting the main array

I have JSON like below, I need to filter out workers having the age less than 25.
var employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
I have tried to use the below code, but it returns all the value inside the workers array, but my expectation is it should return only the employee having than 25.
If I use Map function it is affecting the employee Object also.
var filteredResult = employee.filter(e => e.workers.some(w => w.age < 25))
Expected Result:
{
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
You can do it with a map and a filter, to avoid to modify the original array, you can use Object.asign
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
var filteredResult = employee.value.map(e => {
let filter = e.workers.filter(w => w.age < 25)
return Object.assign({}, e, {workers: filter})
})
console.log('original', employee)
console.log('result', filteredResult)
You could reduce the array and check if the filtered workers have some elements then push a new object with changed workers to the result set.
var employee = { value: [{ position: "Seniro Developer", description: "Developemwnt", workers: [{ name: "Kumar", age: 22 }, { name: "aravinth", age: 29 }, { name: "sathish", age: 35 }] }, { position: "Tester", description: "testing", workers: [{ name: "vinth", age: 18 }, { name: "rahul", age: 45 }, { name: "sathish", age: 12 }] }] },
value = employee.value.reduce((r, o) => {
const workers = o.workers.filter(({ age }) => age < 25);
if (workers.length) r.push({ ...o, workers });
return r;
}, []),
result = { value };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also try this:
var employee = { "value": [ { "position": "Seniro Developer", "description": "Developemwnt", "workers": [ { "name": "Kumar", "age": 22 }, { "name": "aravinth", "age": 29 }, { "name": "sathish", "age": 35 } ] }, { "position": "Tester", "description": "testing", "workers": [ { "name": "vinth", "age": 18 }, { "name": "rahul", "age": 45 }, { "name": "sathish", "age": 12 } ] } ]}
result = employee.value.map(({workers, ...rest})=>({...rest, workers:[...workers.filter(k=>k.age<25)]}));
console.log(result);
Use map and while creating the workers key in return object use filter to get employee with age less than 25. map will create an array
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
let filteredEmployee = employee.value.map((item) => {
return {
"position": item.position,
"description": item.description,
"workers": item.workers.filter(elem => elem.age < 25)
}
});
let newObject = Object.assign({}, {
value: filteredEmployee
});
console.log(newObject)
You can use map method with ... rest syntax:
employee.value.map(({workers, ...rest}) => ({...rest,
workers: workers.filter(w => w.age < 25)}));
An example:
let employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
const result = employee.value.map(({workers, ...rest}) => ({...rest, workers: workers.filter(w => w.age < 25)}));
console.log(result);

How to traverse data according to an array?

I am trying to traverse the data according to the show array and print the data to see if it is correct. To traverse the list array corresponding to the show array as follows
I want the effect as follows:
[
{
"name": "A",
"age": "10",
},
{
"name": "B",
"age": "20",
}
]
const data = [{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "A",
"age": "10",
"logo": "aa.png",
"note": "aa"
}, {
"name": "B",
"age": "20",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
}]
function init() {
data.map(res => {
if (res.code == 200) {
console.log(res.data.list)
}
})
}
init();
By iterating show (rather than hard-coding name and age), this code would work also if you change the structure of your template:
const data = [{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "A",
"age": "10",
"logo": "aa.png",
"note": "aa"
}, {
"name": "B",
"age": "20",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
}];
var ans = data[0].data.list.map(item => {
var curr = {};
data[0].data.show.forEach(prop => {
curr[prop] = item[prop];
});
return curr;
});
console.log(ans);
You can use reduce in a shorter way:
const data = [
{
code: "200",
msg: "success",
data: {
list: [
{
name: "A",
age: "10",
logo: "aa.png",
note: "aa"
},
{
name: "B",
age: "20",
logo: "bb.png",
note: "bb"
}
],
show: ["name", "age"]
}
}
];
console.log(data[0].data.list.map(x =>
data[0].data.show.reduce((p, c) => ((p[c] = x[c]), p), {})
));
const data = [{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "A",
"age": "10",
"logo": "aa.png",
"note": "aa"
}, {
"name": "B",
"age": "20",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
}];
function init() {
data.map(res => {
if (res.code == 200) {
console.log(res.data.list.map(function(listValue) {
var ret = {};
res.data.show.forEach(function(idx) {
ret[idx] = listValue[idx]
});
return ret;
}));
}
})
}
init();
You can use .map on your data and return false if the code isn't 200, if it is 200, you can return a mapped version of your list array. You can map this array to a subset of each object in your list. The subset is defined by your show array, and so you can use .reduce() on this array to build your mapped object.
See example below:
const data = [{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "A",
"age": "10",
"logo": "aa.png",
"note": "aa"
}, {
"name": "B",
"age": "20",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
}];
function init() {
return data.map(res => {
if (res.code == 200) {
return res.data.list.map((obj) => {
return res.data.show.reduce((acc, prop) => ({...acc, [prop]: obj[prop]}), {});
});
}
return false;
}).filter(Boolean); // filter out any `false` returns
}
console.log(init());
Alternatively, a better approach than mapping your original data would be to use .reduce(). This will create a one-dimensional array of results:
const data = [{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "A",
"age": "10",
"logo": "aa.png",
"note": "aa"
}, {
"name": "B",
"age": "20",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
},
{
"code": "200",
"msg": "success",
"data": {
"list": [{
"name": "C",
"age": "30",
"logo": "aa.png",
"note": "aa"
}, {
"name": "D",
"age": "40",
"logo": "bb.png",
"note": "bb"
}],
"show": [
"name",
"age"
]
}
}];
function init() {
return data.reduce((acc, res) => {
if (res.code == 200) {
return [...acc, ...res.data.list.map((obj) => {
return res.data.show.reduce((acc, prop) => ({...acc, [prop]: obj[prop]}), {});
})];
}
return acc;
}, []);
}
console.log(init());
If you want to show only name and age as
[
{
"name": "A",
"age": "10",
},
{
"name": "B",
"age": "20",
}
]
Array.map can be used
and then you can write your code this way
const data = [
{
code: '200',
msg: 'success',
data: {
list: [
{
name: 'A',
age: '10',
logo: 'aa.png',
note: 'aa'
},
{
name: 'B',
age: '20',
logo: 'bb.png',
note: 'bb'
}
],
show: ['name', 'age']
}
}
]
function init() {
data.map(res => {
if (res.code == 200) {
console.log(
res.data.list.map(item => {
return {
name: item.name,
age: item.age
}
})
)
}
})
}
init()
Does this answer your question?

Categories