Recreate array on basis of object's child - javascript

Some time ago I asked a question about how to filter array based on its key today this function but i am working a new implementation that I'm doing.
create array on basis of object's child
But I'm doing a refactoring of how I treat the field value because before I just need the first object and its value [0].value now I need to expand this logic to work with array I'll leave some examples below.
My Code I'm currently using
https://codesandbox.io/s/lodash-tester-forked-fcdmy1?file=/index.js
Original, unfiltered data from API:
[
{
"_id" : ObjectId("62548802054c225fe560f41a"),
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
]
Expected result for table data:
[
{
"_id" : "62548802054c225fe560f41a",
"test1":"taetea",
"test2":"atty",
"Peso":"255"
},
{
...
},
]
Anyone who can help I'm grateful I will repay with rep+ and my eternal thanks xD

As i understand,you want to use title property from the table Columns & search it in the API data.If the title property represents an array of strings,then add all the strings otherwise add the value property.
const apiData = [
{
"_id" : "62548802054c225fe560f41a",
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
];
const tableData = [
{
title: "Peso",
dataIndex: "peso",
key: "peso",
},
{
title: "test",
children: [
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
],
},
];
const tableKeys = tableData.map(t => t.title)
const output = []
apiData.forEach(obj => {
const data = []
Object.keys(obj).filter(key => tableKeys.includes(key)).forEach(key =>{
if(typeof obj[key][0]=== 'string'){
data.push(...obj[key].map((val,index) => ({[`${key}${index+1}`]:val})))
}else{
data.push({[key]: obj[key][0].value})
}
})
// Add the id of the the api data & spread the objects collected
output.push({'_id':obj._id,
...data.reduce((map,elem)=>({...map,...elem}),
{})})
})
console.log('output',output)

Related

Sort array object based on another array in javascript

How can i sort and rearrange an array that looks like this
fields = [
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"
},
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
}
]
to match the arrangement of this array:
order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]
Here is the output I’m looking for:
[
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"),
}
]
findIndex and sort but I am very confused
fields.sort((a: any, b: any) => order.indexOf(a.field) - order.indexOf(b.field)) // It does not work
You need to use sort method on the array. And then compare the index of field on the order array.
const data = [
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: "6283cb3ca573a56e11587c46",
value: 'test val 6'
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: "627f816d8443318c6aaa1220",
value: ''
}
]
const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ];
data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field));
console.log(data);
Notice: ObjectId class is not defined here, so I changed it to string here for simplicity.

How do I populate an array of objects where every object has an array inside of it using response from rest API?

I can't google the right solution for this for about an hour straight,
So I'm getting a response from the API that looks like this:
[
{
"Name": "name1",
"Title": "Name One",
"Children": [
{
"Name": "Name 1.1",
"Title": "Name one point one"
},
]
And I need it to fit this kind of "mold" for the data to fit in:
{
title: 'Name One',
value: 'name1',
key: '1',
children: [
{
title: 'Name one point one',
value: 'Name 1.1',
key: 'key1',
},
I am trying to achieve this using a foreach but It's not working as intended because I need to do this all in one instance of a foreach.
Here's what I gave a go to(vue2):
created() {
getData().then(response => {
const formattedResponse = []
response.forEach((el, key) => {
formattedResponse.title = response.Title
formattedResponse.name = response.Name
formattedResponse.children = response.Children
})
})
Use map over the main array and use destructuring assignment to extract the properties by key, and relabel them, and then do exactly the same with the children array. Then return the updated array of objects.
const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]}];
const result = data.map((obj, key) => {
const { Title: title, Name: value } = obj;
const children = obj.Children.map(obj => {
const { Title: title, Name: value } = obj;
return { title, value, key: (key + 1).toString() };
});
return { title, value, children };
});
console.log(result);
Your API response is JSON. All you need to do is:
var resp=JSON.parse(API response);

Fetch multiple properties from an array of objects and form a new one : Javascript

Been trying to do the following thing:
I have an array of objects ,
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
Would want to fetch the "text" and "field" out of it and form a new array of objects something like this:
result = [ { "field" : "firstName" , value : "aabFaa" , type :"add"},
{ "field" : "firstName" , value : "aAaaaa" , type: "add"}
]
Here type is hard coded one, where as rest are fetched from the "arr"
Whats the easier way to do this?
Have tried this:
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
let result = arr.map(a => a.text);
console.log(result)
But this has to be written in multiple lines to get desired properties.Is there an easier approach?
use map with Object Destructuring.
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
const output = arr.map(({field, text}) => ({field, value: text, type: "add"}));
console.log(output);
Using map seems like a good approach, but you would return a new object and not just one property:
let result = arr.map(a => ({value: a.text, type: 'add', field: a.field}));
let result = arr.map(obj => ({
field: obj.field,
value: obj.text,
type: "add"
}));

REACTJS: obj.push() and obj.concat is not a function

I am having an error that my obj.push() and obj.concat() is not a function but I am not so sure why. Here is my code:
onSearch = () => {
var obj = {
product: [
{
field: "is_published",
filter_value: 1
},
{
field: "order_mode",
filter_array: [
"fcfs",
"purchase-order"
]
},
{
relationship: "store",
filter_object: {
field: "slug",
filter_value: "sample"
}
}
]
}
if (this.state.search !== "") {
obj.push(
{
field: "name",
text_search: this.state.search
}
)
}
var obj2 = {
taxonomies: [
[
{ field: "type",
filter_value: "seller"
},
{ field: "slug",
filter_value: "brand"
}
]
]
}
var conc = obj.concat(obj2);
var { getProductSearch } = this.props
getProductSearch(obj.concat(obj2))
}
product and taxonomies are stored in different variables but I need to pass them as one array to getProductSearch and for that, I need to use concat(). then I need to use push() because I want to add an object to the array obj. What am I doing wrong?
The simple answer is because you can't push onto an object. Push is used for arrays.
To make this work you could instead change your code to push onto the array in your object by doing.
obj.product.push(
{
field: "name",
text_search: this.state.search
}
)
If you are trying to make product dynamic where there are multiple products like [fruits, veggies, meat] then you could change it simply by doing
onSearch(productName)
obj[productName].push(
{
field: "name",
text_search: this.state.search
}
)
This would let you call onSearch(veggies) and push only to that array if you set it up that way.

Sort collections of docs By the biggest embedded Doc with mongodb

I have this schema with mongoose
schema = new Schema({
id: {
type: String,
},
embedded: [embeddedSchema]
});
embeddedSchema = new Schema({
value: {
type: String,
},
});
This can produce something like :
{
"_id" : ObjectId("5454f4f1073cc3b529320f79"),
"embedded" : [
{
"value" : 123,
} , {
"value" : 123,
},
{
"value" : 123423,
}
]
}
/* 1 */
{
"_id" : ObjectId("5454f508910ef3b82970f11d"),
"embedded" : [
{
"value" : 1,
} , {
"value" : 2,
},
{
"value" : 9999999,
}]
}
I would like to sort the schema collection by the biggest value of embedded doc.
Which query can produce this kind of result ?
Thanks you!
When you sort descending on an array element field like value, MongoDB uses the maximum value of that field among all elements in the array.
So in this case it would be:
MyModel.find().sort('-embedded.value').exec(callback);

Categories

Resources