React Js array manipulation - javascript

hope you are doing fine
i came across to a problem of data array manipulation at starting there was not much manipulation required as work progressed now more data manipulation is required and i am running short on this(as a fresher early days of my career
problem explanation - as data i am receiving an array of object and each object contains another array of information (key-value pair) and that array also contains another array of information(key value pair ) and requirement is to i have to loop main data object-item with respect to length of deep nested array and display them on front except this i have done the most part.
i am attaching a sample code of my problem below i am requesting you guys to provide solution for this issue
`
import React, { useState } from "react";
const data = [
{
id: 1,
name: "Something Goes here",
address: "Earth",
arr1: [
{
newId: 1,
title: "Title 1",
midName: "Nothing",
arr2: [
{
subId: 1,
goes: "Hello",
ollo: "Not what you think",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you",
},
],
},
],
},
{
id: 2,
name: "Something Goes",
address: "Mars",
arr1: [
{
newId: 3,
title: "Title sddsdsad",
midName: "Nothing",
arr2: [
{
subId: 2,
goes: "Hello adasdasdasd",
ollo: "Not what you think asdasdasdawd",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you asdasasd",
},
],
},
],
},
];
const App = () => {
const [dummy, setDummy] = useState([]);
let dummyArr = [],
tempObj,
temp;
const tempFunc = () => {
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].arr1; j++) {
for (let k = 0; k < data[i].arr1[j].arr2; k++) {
temp = data[i].arr1[j].arr2[k];
delete data[i].arr1[j].arr2[k];
tempObj = { ...temp ,...data[i], };
dummyArr.push(tempObj);
tempObj = {};
console("tempObj -->", tempObj);
}
}
}
};
console.log("dummyArr", dummyArr);
return (
<React.Fragment>
<button>Hello oooo</button>
</React.Fragment>
);
};
export default App;
expected result is to have both arrays pushed into main itemObject
`
const sampleArray = [
{
id: 2,
name: "Something Goes",
address: "Mars",
newId: 3,
title: "Title sddsdsad",
midName: "Nothing",
subId: 2,
goes: "Hello adasdasdasd",
ollo: "Not what you think asdasdasdawd",
},
];

This code can help you achieve a nested level of any key array and make its single level of array list with extract the keys of non-array value.
The above answer is only limited to nested, but this code is not limited to level what you have and what key has an array value it will iterate and n level of tress
Thanks
const data = [
{
id: 1,
name: "Something Goes here",
address: "Earth",
arr1: [
{
newId: 1,
title: "Title 1",
midName: "Nothing",
arr2: [
{
subId: 1,
goes: "Hello",
ollo: "Not what you think",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you",
},
],
},
],
},
{
id: 2,
name: "Something Goes",
address: "Mars",
arr1: [
{
newId: 3,
title: "Title sddsdsad",
midName: "Nothing",
arr2: [
{
subId: 2,
goes: "Hello adasdasdasd",
ollo: "Not what you think asdasdasdawd",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you asdasasd",
},
],
},
{
newId: 4,
title: "Title sddsdsad1",
midName: "Nothing",
arr2: [
{
subId: 2,
goes: "Hello adasdasdasd",
ollo: "Not what you think asdasdasdawd",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you asdasasd",
},
],
},
],
},
];
function getArrayHasValue(obj) {
const keys = Object.keys(obj).filter(accu => Array.isArray(obj[accu]))
return keys[0] ? keys[0] : null;
}
function getObjecNoNested(obj) {
const keys = Object.keys(obj).filter(accu => !Array.isArray(obj[accu]))
return keys
}
function unwindArray(arr, queue,ref) {
for (let i of arr) {
const nestedArrayKayname = getArrayHasValue(i)
const nonNestedKeys = getObjecNoNested(i)
ref = JSON.parse(JSON.stringify(ref))
if (nestedArrayKayname) {
nonNestedKeys.forEach(elem => {
ref[`${elem}`] = i[elem]
})
unwindArray(i[nestedArrayKayname], queue, ref)
}else {
nonNestedKeys.forEach(elem => {
ref[`${elem}`] = i[elem]
})
queue.push(ref)
}
}
return queue
}
console.log(unwindArray(data, [],{}))

Try this
const yourData = [
{
id: 1,
name: "Something Goes here",
address: "Earth",
arr1: [
{
newId: 1,
title: "Title 1",
midName: "Nothing",
arr2: [
{
subId: 1,
goes: "Hello",
ollo: "Not what you think",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you",
},
],
},
],
},
{
id: 2,
name: "Something Goes",
address: "Mars",
arr1: [
{
newId: 3,
title: "Title sddsdsad",
midName: "Nothing",
arr2: [
{
subId: 2,
goes: "Hello adasdasdasd",
ollo: "Not what you think asdasdasdawd",
},
{
subId: 2,
goes: "Hello 2",
ollo: "Not what you asdasasd",
},
],
},
],
},
];
const tempFunc = (yourData) => {
const result = [];
for(let data of yourData){
const temp ={...data, ...data.arr1[0], ...data.arr1[0].arr2[data.arr1[0].arr2.length-1]};
delete temp.arr1;
delete temp.arr2;
result.push(temp);
}
return result;
};
console.log(tempFunc(yourData));

Related

Why object is getting returned when applied map and filter to match the string search in available nested json data

I am returning the objects which have the card titles matches with the searched value from available data.
Data JSON :
let state = {rawData : [
{
"id": 1,
"title": "To Do",
"cards": [
{
"id": 111,
"title": "Team Meeting"
},
{
"id": 112,
"title": "DB Design"
}
]
},
{
"id": 2,
"title": "Doing",
"cards": [
{
"id": 221,
"title": "Raman's Review"
},
{
"id": 222,
"title": "Sequence Diagram"
}
]
},{
"id": 3,
"title": "Done",
"cards": [
{
"id": 331,
"title": "Karan's Review"
},{
"id": 332,
"title": "Karan"
}
]
}
]}
Here, As you can see rawData consist 3 objects each have cards array object.
Now, filter out the cards data which had a consist the search value. Please refer below code. To know how I am trying filter it and actual output I am getting Also the output I want.
var searchVal = "K"
let val = state.rawData.map(list => {
let out = list.cards.filter(card => card.title.toLowerCase().includes(searchVal.toLowerCase()))
let x = {...list}
x.cards =[...out]
console.log(x)
return x;
})
console.log(val)
As you can see above. I have a search str as "K". I am mapping over the each rawData object and using filter checking if the value is entered search string is available in card.title or not.
console result of x:
{ id: 1, title: 'To Do', cards: [] }
{ id: 2, title: 'Doing', cards: [] }
{
id: 3,
title: 'Done',
cards: [ { id: 331, title: "Karan's Review" }, { id: 332, title: 'Karan' } ]
}
Here, I am getting the result I want. But when I returns the x. The output is below:
[
{ id: 1, title: 'To Do', cards: [] },
{ id: 2, title: 'Doing', cards: [] },
{ id: 3, title: 'Done', cards: [ [Object], [Object] ] }
]
Please not here the cards are returned as objects. Not sure why this is happening.
The result I want :
[
{ id: 1, title: 'To Do', cards: [] }
{ id: 2, title: 'Doing', cards: [] }
{
id: 3,
title: 'Done',
cards: [ { id: 331, title: "Karan's Review" }, { id: 332, title: 'Karan' } ]
}
]
I need some help in understanding the reason behind/way around to resolve the issue.

How to traverse through 2 javascript array of objects and create a third one?

I have two objects. obj2 has texts and obj1 has 3 subIbjId. How can I add the 'id' to obj2 based on obj1?
For example: obj1 has 2 subObjId in the first object(1001, 1002). I want to count the number of subObjId obj1 has and iterate through obj1 and add the key and value of id for the to obj2. If obj1 has two subObjId, then add id: 1 to the first two entries of obj2 and so on.
I am learning javascript and trying to solve some imaginary problems. Any help would be greatly appreciated. Thank you.
var obj1 = { [
{
id: 1,
name: ‘apple’,
subObjId: [ 1001, 1002]
subObjs: [
{
subId: 1001
subName: ‘ant’,
},
{
subId: 1002
subName: ‘ball’,
}
],
},
{
{
id: 2,
name: ‘zebra’,
subObjId: [ 1003]
subObjs: [
{
subId: 1003
subName: ‘cat’,
}
],
},
]
}
var obj2 = { [
{
text: ‘i am a text’
},
{
text: ‘i am some random characters’
},
{
text: ‘i am some numbers’
}
] }
to become
finalObject = { [
{
id: 1,
text: ‘i am a text’
},
{
id: 1,
text: ‘i am some random characters’
},
{
id: 2,
text: ‘i am some numbers’
}
] }
Try this!!
var obj1 = [
{
id: 1,
name: 'apple',
subObjId: [ 1001, 1002]
},
{
id: 2,
name: 'zebra',
subObjId: [ 1003]
}
]
var obj2 = [
{
text: 'i am a text'
},
{
text: 'i am some random characters'
},
{
text: ' am some numbers'
}
]
let index = 0;
let start = 0;
obj1.map(data1=>{
index += data1.subObjId.length;
for(var i=start;i<index;i++){
obj2[i]['id'] = data1.id;
}
start = i;
})
console.log(obj2)
You can use
Array#flatMap to extract an array of all subObjs items
also Array#map them into their parent's id property only.
Perform another mapping operation that copies the contents of a matching object in obj2 and adds an id.
For convenience, this uses the second argument to Array#map, which sets the this context inside the callback.
Also uses destructuring for compactness and spread syntax for making copies:
var obj1 = [ { id: 1, name: 'apple', subObjId: [1001, 1002], subObjs: [ { subId: 1001, subName: 'ant' }, { subId: 1002, subName: 'ball' } ] }, { id: 2, name: 'zebra', subObjId: [1003], subObjs: [ { subId: 1003, subName: 'cat', } ], }, ];
var obj2 = [ { text: 'i am a text' }, { text: 'i am some random characters' }, { text: 'i am some numbers' } ];
var finalObject = obj1
//1. flatMap into a single array
.flatMap(({id, subObjs}) => subObjs
.map(sub => ({id})) //take only the parent ID for each sub object
)// result: [{id: 1}, {id: 1}, {id: 2}]
.map(function({id}, index) {
return { id, ...this[index] } //2. create a new object with the id and the content of a matching object from the other array
}, obj2);// <- set the `this` context for the callback
console.log(finalObject);
It can also be done as a single operation when flatmapping by setting the this context to a copy of the second array (to avoid mutating obj2), then taking items off the front of the new array with Array#shift:
var obj1 = [ { id: 1, name: 'apple', subObjId: [1001, 1002], subObjs: [ { subId: 1001, subName: 'ant' }, { subId: 1002, subName: 'ball' } ] }, { id: 2, name: 'zebra', subObjId: [1003], subObjs: [ { subId: 1003, subName: 'cat', } ], }, ];
var obj2 = [ { text: 'i am a text' }, { text: 'i am some random characters' }, { text: 'i am some numbers' } ];
var finalObject = obj1.flatMap(function({id, subObjs}) {
return subObjs.map(sub => ({ id, ...this.shift() }))
}, [...obj2]);// <- copy obj2 as the `this` context
console.log(finalObject);
Use this snippet
var obj1 = [
{
id: 1,
name: 'apple',
subObjId: [1001, 1002],
subObjs: [{
subId: 1001,
subName: 'ant',
},
{
subId: 1002,
subName: 'ball',
}
],
},
{
id: 2,
name: 'zebra',
subObjId: [1003],
subObjs: [{
subId: 1003,
subName: 'cat',
}],
},
]
var obj2 = [
{
text: 'i am a text'
},
{
text: 'i am some random characters'
},
{
text: 'i am some numbers'
}
]
var finalObject = obj1.map(function (value, index) {
return {
id: value.id,
text: obj2[index].text
}
})
console.log(finalObject)

React: group by multidimensional array object by value in component

How to group multidimensional array objects by value in the component.
I need to group array by page and get the text for every page. I tray to use the map and reduce it but don't get good results. I work on react-native project. JS function groups doesn't work for some reason.
What is the best way to write code for this array?
I have this array:
[
{
number: 1,
englishName: 'Name 1',
items: [
{
text: 'Some text',
page: 1,
},
{
text: 'Some text',
page: 1,
},
],
},
{
number: 2,
englishName: 'Name 2',
items: [
{
text: 'Some text',
page: 2,
},
{
text: 'Some text',
page: 2,
},
],
},
{
number: 3,
englishName: 'Name 3',
items: [
{
text: 'Some text',
page: 3,
},
{
text: 'Some text',
page: 4,
},
],
},
]
I need an array like this
[
{
'page 1': [
{
text: 'Some text',
englishName: 'Name 1',
},
{
text: 'Some text',
englishName: 'Name 2',
},
],
},
{
'page 2': [
{
text: 'Some text',
englishName: 'Name 2',
},
{
text: 'Some text',
englishName: 'Name 2',
},
],
},
....
]
Seems like this will work for you.
This will give you an object:
const allPages = array.reduce((acc, curr) => {
curr.items.forEach((page) => {
var pageKey = `page ${page.page}`
if(!acc[pageKey]){
acc[pageKey] = []
}
acc[pageKey].push({ text: page.text, englishName: curr.englishName })
})
return acc
}, {})
You can convert that object into an array as well:
const finalArr = Object.entries(allPages).map(([page, array]) => {
return {
[page]: array
}
})
See example:
var array = [{
"number": 1,
"englishName": "Name 1",
"items": [
{
"text": "Some text",
"page": 1,
},
{
"text": "Some text",
"page": 1,
}
]
},
{
"number": 2,
"englishName": "Name 2",
"items": [
{
"text": "Some text",
"page": 2,
},
{
"text": "Some text",
"page": 2,
}
]
},
{
"number": 3,
"englishName": "Name 3",
"items": [
{
"text": "Some text",
"page": 3,
},
{
"text": "Some text",
"page": 4,
}
]
}
]
const allPages = array.reduce((acc, curr) => {
curr.items.forEach((page) => {
var pageKey = `page ${page.page}`
if(!acc[pageKey]){
acc[pageKey] = []
}
acc[pageKey].push({ text: page.text, englishName: curr.englishName })
})
return acc
}, {})
const finalArr = Object.entries(allPages).map(([page, array]) => {
return {
[page]: array
}
})
console.log(allPages)
console.log(finalArr)

javascript - merge, combine, transform 2 different arrays of Objects

I can't figure it out how to transform and combine 2 arrays of object.
I have this 2 arrays of objects:
const selectedCourse = [
{
"courseType": [5],
"id": 26,
"title": "Apple Tart with Apricot Glaze",
},
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
},
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
]
const courseTypes = [
{name: "Hors d'oeuvres", id: 0},
{name: "Soup", id: 1},
{name: "Fish", id: 2},
{name: "Salad", id: 3},
{name: "Main course", id: 4},
{name: "Dessert", id: 5}
]
The courseType property inside the first JSON is an array of numbers that corresponds to courseTypes index and property id in the second JSON.
The result for this case should be this:
const result = [
{
courseType: 1,
courseName: "Soup",
courses: [
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
}
]
},
{
courseType: 3,
courseName: "Salad",
courses: [
{
"courseType": [1,2],
"id": 10,
"title": "Lobster Bisque",
}
]
},
{
courseType: 3,
courseName: "Fish",
courses: [
{
"courseType": [3],
"id": 16,
"title": "Classic Caesar Salad",
},
{
"courseType": [3],
"id": 16,
},
]
},
{
courseType: 5,
courseName: "Main course",
courses: [
{
"courseType": [5],
"id": 26,
"title": "Apple Tart with Apricot Glaze",
}
]
}
]
The expected result have to combine the 2 arrays by filtering by courseType property.
Assuming, you want all items with selectedCourse, you could take a Map and collect all courses and later greate a new array out of the found values.
This solution includes Fish as well.
const
selectedCourse = [{ courseType: [5], id: 26, title: "Apple Tart with Apricot Glaze" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }, { courseType: [1, 2], id: 10, title: "Lobster Bisque" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }],
courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }],
map = selectedCourse.reduce((m, o) => o.courseType.reduce((n, id) => n.set(id, [...(n.get(id) || []), o]), m), new Map),
result = courseTypes.reduce(
(r, { name: courseName, id: courseType }) => (map.get(courseType) || []).reduce((s, courses) => s.concat({ courseType, courseName, courses }), r),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use map and filter like this:
const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]
const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];
const result = courseTypes.map(courseType => ({
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(course => course.courseType.includes(courseType.id))
})).filter(extended => extended.courses.length);
console.log(JSON.stringify(result, null, 2));
Explanation:
courseTypes.map iterates over your second input array and for each type it finds in selectedCourse which courses match with that particular type.
It uses .filter to collect those matches. The filter callback uses includes to determine if there is a match -- it returns a boolean, exactly what the filter callback expects as return value.
This filtered array is then added to an object literal that also defines the other two properties courseType and courseName. That new object is what the course type is mapped to. courseTypes.map returns an array of those objects.
Finally that result may have entries that have an empty courses array. Those are filtered out with another call to .filter. If the length of that courses array is non zero, the object is kept, otherwise it is kicked out of the result.
For older browsers
Here is the same code made compatible with older browsers (no arrow functions, no includes, which were introduced in ES2015):
const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]
const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];
const result = courseTypes.map(function (courseType) {
return {
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(function (course) {
return course.courseType.indexOf(courseType.id) > -1;
})
};
}).filter(function (extended) {
return extended.courses.length;
});
console.log(JSON.stringify(result, null, 2));
while "trincot" code is work fine for chrome and Mozila but it will not work in IE edge and IE 10 and below you need to convert it in pure javascript. below is code which will work in all browser.
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
var selectedCourse = [{ "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }, { "courseType": [1, 2], "id": 10, "title": "Lobster Bisque" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }];
var courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }];
var result = courseTypes.map(function (courseType) {
return {
courseType: courseType.id,
courseName: courseType.name,
courses: selectedCourse.filter(function (course) {
return course.courseType.includes(courseType.id);
})
};
}).filter(function (extended) {
return extended.courses.length;
});
console.log(JSON.stringify(result, null, 2));

Normalizr with nested array of objects

I have a nested array of objects like this:
var matchs = [
{
id: 10689,
sport: 'Tennis',
players: [
{
id: 22,
name:'Rafa Nadal',
country: 'Spain',
odds: [
{id: 1, bookie_1: 1.60},
{id: 2, bookie_2: 1.61},
{id: 3, bookie_3: 1.62},
]
},
{
id: 23,
name:'Roger Federer',
country: 'Spain',
odds: [
{id: 4, bookie_1: 2.60},
{id: 5, bookie_2: 2.61},
{id: 6, bookie_3: 2.62},
]
}
]
},
{
id: 12389,
sport: 'Tennis',
players: [
{
id: 45,
name:'Fernando Verdasco',
country: 'Spain',
odds: [
{id: 7, bookie_1: 2.60},
{id: 8, bookie_2: 2.61},
{id: 9, bookie_3: 2.62},
]
},
{
id: 65,
name:'Andy Murray',
country: 'Spain',
odds: [
{id: 10, bookie_1: 1.60},
{id: 11, bookie_2: 1.61},
{id: 12, bookie_3: 1.62},
]
}
]
}
];
I want to use normalizr to simplify array and use with redux. I have read the Normalizr documentation but it has few examples and I do not know what I am doing wrong.
I have tried the following code without success. The result I get is an array with undefined.
import { normalize, schema } from 'normalizr';
const match = new schema.Entity('matchs');
const player = new schema.Entity('players');
const odd = new schema.Entity('odds');
match.define({
player: [player],
odd: [odd]
});
console.log(normalize(matchs, [match]));
I need something like this:
{
result: "123",
entities: {
"matchs": {
"123": {
id: "123",
players: [ "1","2" ],
odds: [ "1", "2" ]
}
},
"players": {
"1": { "id": "1", "name": "Rafa Nadal" },
"2": { "id": "2", "name": "Andy Murray" }
},
"odds": {
"1": { id: "1", "bookie_1": "1.20" }
"2": { id: "2", "bookie_2": "1.21" }
"3": { id: "3", "bookie_3": "1.22" }
}
}
}
I cannot find a straight solution using only normalizr, so my only choice is to pre-format the data before passing to the normalizer.
const preformattedData = data.map(sport => {
const oddArrays = sport.players.map(player => player.odds || []);
return {
...sport,
odds: [].concat.apply([], oddArrays)
}
})
const odd = new schema.Entity('odds')
const player = new schema.Entity('players',
{
odds: [ odd ]
}
)
const sport = new schema.Entity('sports',
{
players: [ player ],
odds: [odd]
}
)
const normalizedData = normalize(preformattedData, [ sport ]);
Demo: https://codesandbox.io/s/20onxowzwn
I think this is what you need
const odd = new schema.Entity('odds');
const player = new schema.Entity('players' , { odds: [ odd]});
const match = new schema.Entity('matchs', {players: [player]});
but the result will be different because your json it is structured like this, I mean, the odds key is child of players, not of matches, therefore the result will be this way.
Just take a look at the console
Here is a solution with latest version of normalizr
const odds = new schema.Entity("odds");
const players = new schema.Entity("players", {
odds: [odds]
});
const matches = new schema.Entity("matches", { players: [players] });
const normalizedData = normalize(data, [matches]);
It would group data in your question as
{
"entities": {
"odds": {
"1": {
"id": 1,
"bookie_1": 1.6
}
},
"players": {
"22": {
"id": 22,
"name": "Rafa Nadal",
"country": "Spain",
"odds": [
1,
2,
3
]
}
},
"matches": {
"10689": {
"id": 10689,
"sport": "Tennis",
"players": [
22,
23
]
}
}
},
"result": [
10689
]
}
You can achieve your desired result by tweaking the process and merge strategies. I don't have time to do the leg work for you, but I explain the approach in detail here:
https://medium.com/#JustinTRoss/normalizing-data-into-relational-redux-state-with-normalizr-47e7020dd3c1

Categories

Resources