I have getting the data from database as an array.
So now I'm getting array like this:
orders:[
{
_id:1,
name: honda,
}
{
_id:2,
name: suzuki,
}
{
_id:3,
name: audi,
}
]
So my question is how can I attach new key value to the array, so It needs to look like this:
orders:[
{
_id:1,
name: honda,
opened:true,
}
{
_id:2,
name: suzuki,
opened:true,
}
{
_id:3,
name: audi,
opened:true,
}
]
For now I'm trying with this code, but this doesn't work:
getOrders(orders).then(response => {
response.map(itm=>{
const ordersData=[...itm]
const opened={opened:true}
this.setState({
openedOrders: [ordersData,opened]
})
})
})
openedOrders is new state object that I create.
What is best solution for this?
Thanks
Your map should look like this. (Note the return statement in map function)
orders.map(item=> {
return {...item, opened:true}
})
So your function could look like
getOrders(orders).then(response => {
let openedOrders = orders.map(item=> {
return {...item, opened:true}
})
this.setState({
openedOrders
})
})
Assuming response contains the first array in your OP:
getOrders(orders).then(response => {
const openedOrders = response.map(order => ({ ...order, open: true}))
this.setState({ openedOrders } )
})
response.map(order => ({ ...order, open: true}) adds a key open with the value true to every order in the array.
To add dynamic keys to a object in javascript we use [].
var x = [{ _id : 1, name: Suzuki}];
x[0]['opened'] = true;
console.log(x);
// [{ _id : 1, name: Suzuki, opened: true}];
Use foreach() to loop through all the orders in the array and add the desired property for each order.
let orders = [{
_id: 1,
name: 'honda',
}, {
_id: 2,
name: 'suzuki',
}, {
_id: 3,
name: 'audi',
}]
orders.forEach(o => o.opened = true)
console.log(orders)
You could add a new property to the objects.
var orders = [{ _id: 1, name: 'honda' }, { _id: 2, name: 'suzuki' }, { _id: 3, name: 'audi' }],
additionalProp = { opened: true };
orders.forEach(o => Object.assign(o, additionalProp));
console.log(orders);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Or map a new array without mutating the original objects.
var orders = [{ _id: 1, name: 'honda' }, { _id: 2, name: 'suzuki' }, { _id: 3, name: 'audi' }],
additionalProp = { opened: true },
result = orders.map(o => Object.assign({}, o, additionalProp));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I have a question about how I can delete the existing elements, for example, in my case "Tallas" is repeated, could you please help me? Thank you very much to those who are willing to help me to solve this problem
const data =
[ { atributos: { Tallas: [{ id: 0, name: 'XS' }, { id: 1, name: 'S' }] }}
, { atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }}
, { atributos: { Tallas: [{ id: 0, name: 'XS' }] }}
]
The idea is to have this json format with the last "Tallas" since it is the last one that I added through my dynamic form.
const expected =
[{ atributos: { Calzado: [{ id: 0, name: '10' }, { id: 1, name: '9.5' }] }}
, { atributos: { Tallas: [{ id: 0, name: 'XS' }] }}
]
How do I do this is there a way to do it, I've tried with filter plus the findindex but I can't get to eliminate the repetition of the json res= new.filter((arr, index, self) => index === self.findIndex( (t) => (t.attributes === arr.attributes )))
To unique the array of objects, we can use the Javascript Set module, if the array has complex nested objects, we can stringify each object before creating new Set data. this below function will unique the array of complex objects.
function unique_array(array = []) {
const newSetData = new Set(array.map((e) => JSON.stringify(e)));
return Array.from(newSetData).map((e) => JSON.parse(e));
}
this is a function that takes an array and return the same array but delete every duplicated item
function removeDuplicates(arr) {
return arr.filter((item,
index) => arr.indexOf(item) === index);
}
I didn't understant the part written in spanish so I hope this is what you are looking for
This is a solution specific to your question. this is not a generic solution.
const data = [
{
atributos: {
Tallas: [
{ id: 0, name: "XS" },
{ id: 1, name: "S" },
],
},
},
{
atributos: {
Calzado: [
{ id: 0, name: "10" },
{ id: 1, name: "9.5" },
],
},
},
{
atributos: {
Tallas: [
{ id: 0, name: "XS" },
{ id: 1, name: "S" },
],
},
},
];
function uniqueArray(array) {
const resultObject = array.reduce((acc, eachValue) => {
let keys = Object.keys(eachValue.atributos);
keys.forEach((eachKey) => {
if (!acc[eachKey]) {
acc[eachKey] = [];
}
let list = eachValue["atributos"][eachKey].map(
(each) => each.id + "-" + each.name
);
acc[eachKey].push(...list);
});
return acc;
}, {});
const resultArray = Object.keys(resultObject).reduce((acc, each) => {
let setData = Array.from(new Set(resultObject[each]));
acc.push({
atributos: {
[each]: setData.map((e) => {
return { id: e.split("-")[0], name: e.split("-")[1] };
}),
},
});
return acc;
}, []);
return resultArray;
}
const result = uniqueArray(data)
console.log("result ", JSON.stringify(result, null, 2));
let a =
[
{
Name: 'Josh',
Subject: ['Biology', 'Chemistry'],
},
{
Name: 'James',
Subject: ['Chemistry', 'Physics'],
},
{
Name: 'Mary',
Subject: ['Physics', 'Mathematics'],
},
]
const result = a.reduce((groupedSubject, person) => {
const Subject = person.Subject
if(groupedSubject[Subject]== null) groupedSubject[Subject] = []
groupedSubject[Subject].push(person)
return groupedSubject
}, {})
console.log(result)
I was able to group according to the subject, but subject is an array. how do i group it by individual subjects?
You need to iterate Sports array as well.
const
data = [{ Name: 'Ravindra', Sports: ['Chess', 'Cricket'] }, { Name: 'Ravi', Sports: ['Cricket', 'Football'] }, { Name: 'Rishabh', Sports: ['Table-Tennis', 'Football'] }],
result = data.reduce((groupedSports, person) => {
person.Sports.forEach(sport => {
groupedSports[sport] ??= [];
groupedSports[sport].push(person.Name);
})
return groupedSports;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can iterate over all sports and check if it already exists, if not, spread all current entries and add the new persons Name to the array.
let a = [{
Name: 'Ravindra',
Sports: ['Chess', 'Cricket'],
},
{
Name: 'Ravi',
Sports: ['Cricket', 'Football'],
},
{
Name: 'Rishabh',
Sports: ['Table-Tennis', 'Football'],
},
]
const result = a.reduce((groupedSports, person) => {
person.Sports.forEach((sport) => {
groupedSports[sport] = groupedSports?.[sport]
? [...groupedSports[sport], person.Name]
: [person.Name];
});
return groupedSports;
}, {});
console.log(result)
I need to be able to concatenate two JavaScript objects like the following:
let arr1 = [
{"0": { id: "abdc4051", date: "2017-01-24" }},
{"1": { id: "abdc4052", date: "2017-01-22" }}
];
let arr2 = [
{"0": { category: "Sport", data: {code: "abdc4051", name: "ab"} } },
{"1": { category: "Others", data: {code: "abdc4052", name: "abc"} } }
];
Does anyone have a script for this or know of a built in way to do this?
I want the date to be added in the data on arr2 with the condition code equal to id
Your object shape makes this harder than it should be. Are you certain you want the sequential properties in each object, or is that an artifact of logging/poor parsing?
You'll need to work around them if you actually need them, in the snippet below using Object.values() in creating a Map from arr1, and using Object.entries() in the final map() call on arr2 to store the sequential key and then reintroduce it in the return after the merge logic.
const
arr1 = [{ "0": { id: "abdc4051", date: "2017-01-24" } }, { "1": { id: "abdc4052", date: "2017-01-22" } }],
arr2 = [{ "0": { category: "Sport", data: { code: "abdc4051", name: "ab" } } }, { "1": { category: "Others", data: { code: "abdc4052", name: "abc" } } }],
// create map of dates: Map(2) { 'abdc4051' => '2017-01-24', 'abdc4052' => '2017-01-22' }
dateMap = new Map(arr1.map(o => {
const [{ id, date }] = Object.values(o);
return [id, date];
})),
// map over arr2, get date from Map and add it to 'data' if it exists
result = arr2.map(o => {
const [[k, _o]] = Object.entries(o);
const date = dateMap.get(_o.data.code);
return {
[k]: {
..._o,
data: { ..._o.data, ...(date ? { date } : {}) }
}
};
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you don't need the initial sequential keys the merge becomes much less verbose.
const
arr1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],
arr2 = [{ category: "Sport", data: { code: "abdc4051", name: "ab" } }, { category: "Others", data: { code: "abdc4052", name: "abc" } }],
dateMap = new Map(arr1.map(o => [o.id, o.date])),
result = arr2.map(o => (
{
...o,
data: { ...o.data, ...(dateMap.has(o.data.code) ? { date: dateMap.get(o.data.code) } : {}) }
}
));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an array of objects and each object has an id. I have another array with id values. If an objects id is found in arrayOfIds, I would like to add new property called found and set to true. I was thinking of using findIndex as a possible function to use here.
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']
Expected Output
const arrayOfObjects = [ { id: '123' }, { id: '456', found: true }, { id: '789' } ]
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']
arrayOfObjects.map((object) => {
if(arrayOfIds.includes(object.id)) {
object.found = true;
}
})
console.log(arrayOfObjects);
I think it would make sense to convert your arrayOfIds to a Set to allow O(1) lookup.
const ids = new Set(arrayOfIds);
const augmentedObjects = arrayOfObjects.map(obj => {
if (ids.has(obj.id)) {
obj.found = true;
}
return obj;
});
You can create a Set from the array and use Array#map along with Set#has.
const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const ids = new Set(['456']);
const res = arrayOfObjects.map(o => ({...o, ...ids.has(o.id) && {found: true}}));
console.log(res);
You can map through the objects and spread the object with the found property.
const output = arrayOfObjects.map((obj) => {
if (arrayOfIds.includes(obj.id)) {
return { ...obj, found: true };
}
return obj;
});
You could do it by creating a lookup object. Create the lookup object from arrayOfIds and use that lookup object when traversing arrayOfObjects array and make certain changes.
const arrayOfObjects = [{ id: '123' }, { id: '456' }, { id: '789' }];
const arrayOfIds = ['456'];
const lookup = Object.fromEntries(arrayOfIds.map((x) => [x, { found: true }]));
const ret = arrayOfObjects.map((x) => ({ ...x, ...lookup[x.id] }));
console.log(ret);
Just run a map over the array of objects, and use the includes to add show: true by spreading the existing object else return the original object.
You could try something like this
const arrayOfObjects = [{ id: "123" }, { id: "456" }, { id: "789" }];
const arrayOfIds = ["456"];
const result = arrayOfObjects.map((item) => {
if (arrayOfIds.includes(item.id)) {
return {
...item,
found: true
};
}
return item;
});
console.log(result);
I have the next code:
const arr = [
{
name:'john',
cars:[
{audi:1},
{bmw:2}
]
},
{
name:'bill',
cars:[
{audi:10},
{bmw:0}
]
}
]
const arr1 = arr.map(i => {
if(i.name === 'john') {
return i.cars.map( a => {
return {
...i,
test:[2]
}
})
}
return i
})
console.log(arr1)
Here i want too loop through the array and for the first object to change the cars array, adding test:[2]. For this i used:
const arr1 = arr.map(i => {
if(i.name === 'john') {
return i.cars.map( a => {
return {
...i,
test:[2]
}
})
}
return i
})
The issue is that my code don't return what i want. I get the first object like:
0: Object
name: "john"
cars: Array[2]
test: 2
1: Object
name: "john"
cars: Array[2]
test: 2
but i need like this:
{
name:'john',
cars:[
{
audi:1,
test: [2],
},
{bmw:2}
]
},
How to solve my issue?
Since you only want to change the first item in the cars array, I don't think map is right - instead, just list the first changed car as an object literal inside an array, then spread the remaining cars into the array with .slice(1):
const arr = [
{
name:'john',
cars:[
{audi:1},
{bmw:2}
]
},
{
name:'bill',
cars:[
{audi:10},
{bmw:0}
]
}
]
const arr1 = arr.map(person => (
person.name !== 'john'
? person
: ({
name: person.name,
cars: [
{ ...person.cars[0], test: [2] },
...person.cars.slice(1)
]
})
));
console.log(arr1)
You could address the right position and add the wanted property.
const
data = [{ name: 'john', cars: [{ audi: 1 }, { bmw: 2 }] }, { name: 'bill', cars: [{ audi: 10 }, { bmw: 0 }] }],
add = { target: [0, 0], value: { test: [2] } }
result = data.map((o, i) => i === add.target[0]
? { ...o, cars: o.cars.map((p, j) => j === add.target[1]
? {... p, ...add.value }
: p)
}
: o);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Given the desired result, a non mapping solution may be viable?
const arr = [{
name: 'john',
cars: [{
audi: 1
},
{
bmw: 2
}
]
},
{
name: 'bill',
cars: [{
audi: 10
},
{
bmw: 0
}
]
}
];
// clone the initial arr
const arrModified = Object.assign([], arr);
// find John
const indexJohn = arrModified.findIndex(v => v.name === "john");
if (indexJohn > -1) {
// modify the desired value
arrModified[indexJohn].cars[0].test = [2];
}
console.log(arrModified[0].cars);
.as-console-wrapper { top: 0; max-height: 100% !important; }