Adding new values to an array - javascript

I want to add new values on my array in javascript. The array is like that:
[
0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
This is a simple array, my array is bigger and more values. I want to add new values like that:
[
0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003",
SecondTime: "2020-06-08T11:12:03.003" },
1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003",
SecondTime: "2020-06-08T11:12:03.003" }
]
I know there are a lot of similar questions but i couldn't find any solution to my problem.

using foreach
const data = [
{ Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
{ Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
data.forEach(i=> i.SecondTime = i.Time);
console.log(data)
Using reduce:
const data = [
{ Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" },
{ Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
]
var res = data.reduce((acc, elem)=>{
elem.Secondtime = elem.Time;
return acc = [...acc, elem];
},[]);
console.log(res)

let blah = {
0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003"},
1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }
};
Object.keys(blah).forEach((ele)=>{
blah[ele].SecondTime = "2020-06-08T11:12:03.003"
});
console.log(blah);
Hope this helps

In an alternative to foreach and reduce answers, you can use map. Has you can see here, for changing data, the map has a little better performance over foreach loops or reduce fucntions.
Follows a full working example:
const originalArray = [
{ 0: { Id: 0,
Name: "First",
Time: "2020-06-08T11:12:03.003" }},
{ 1: { Id: 1,
Name: "Second",
Time: "2020-06-08T11:12:03.003" }}
]
const transformedArray = originalArray.map((element, index) => {
element[index].SecondTime = new Date();
return element;
});
console.log(transformedArray);

Related

Filter array of objects by another object's values

I would like to filter an array of objects based on the values in another object. I am trying to map() the array and filter() inside the function so that I am able to get a new array with only the desired (active) fields.
I am trying to get the filter on the Object.entries(), I try to compare the keys and check if the values of the active filters are true, but I am not getting it right.
const records = [
{
id: 1,
name: "first",
date: "05/02"
},
{
id: 2,
name: "second",
date: "06/02"
},
{
id: 3,
name: "third",
date: "07/02"
},
{
id: 4,
name: "fourth",
date: "08/02"
}
];
const active = {
id: true,
name: false,
date: true
};
const result = records.map((record) => {
return Object.entries(record).filter((entry) => {
Object.entries(active).forEach((activeEntry) => {
return activeEntry[1] && activeEntry[0] === entry[0];
});
});
});
console.log(result);
This is the desired outcome
const desiredOutcome = [
{
id: 1,
date: "05/02"
},
{
id: 2,
date: "06/02"
},
{
id: 3,
date: "07/02"
},
{
id: 4,
date: "08/02"
}
];
You can filter over the entries of the object and convert it back to an object with Object.fromEntries.
const records=[{id:1,name:"first",date:"05/02"},{id:2,name:"second",date:"06/02"},{id:3,name:"third",date:"07/02"},{id:4,name:"fourth",date:"08/02"}];
const active = {
id: true,
name: false,
date: true
};
const res = records.map(x =>
Object.fromEntries(
Object.entries(x).filter(([k])=>active[k])));
console.log(res);
Simply filter the keys by the key existing and then use Object.fromEntries to go back to an object
const records = [
{
id: 1,
name: "first",
date: "05/02"
},
{
id: 2,
name: "second",
date: "06/02"
},
{
id: 3,
name: "third",
date: "07/02"
},
{
id: 4,
name: "fourth",
date: "08/02"
}
];
const active = {
id: true,
name: false,
date: true
};
const result = records.map((record) => {
return Object.fromEntries( Object.entries(record).filter(([key,value]) => active[key]));
});
console.log(result);

find an object in Array of Array

if i want for an example loop Through this Array to find specific item in Items Array how to approach that? i made this logic but it doesn't work
DATA.map((D)=>{
return D.items.find((item)=>{
return item.name ==='Blue Beanie'
})
})
this is the Array plus how to create new ONE array includes the both of items arrays to be like that: items: [{
id: 1,
name: 'Brown Brim',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
price: 18
},
{
id: 3,
name: 'Adidas NMD',
price: 220
},
{
id: 4,
name: 'Adidas Yeezy',
price: 280
}
]
const DATA= [
{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
price: 18
}
]
},
{
id: 2,
title: 'Sneakers',
routeName: 'sneakers',
items: [
{
id: 3,
name: 'Adidas NMD',
price: 220
},
{
id: 4,
name: 'Adidas Yeezy',
price: 280
}
]
}
];
Transform DATA into list of items and find from that list your expected item
const res = DATA.flatMap((D) => D.items).find(
(item) => item.name === "Brown Brim"
)
const DATA = [
{
id: 1,
title: "Hats",
routeName: "hats",
items: [
{
id: 1,
name: "Brown Brim",
price: 25,
},
{
id: 2,
name: "Blue Beanie",
price: 18,
},
],
},
{
id: 2,
title: "Sneakers",
routeName: "sneakers",
items: [
{
id: 3,
name: "Adidas NMD",
price: 220,
},
{
id: 4,
name: "Adidas Yeezy",
price: 280,
},
],
},
]
const res = DATA.flatMap((D) => D.items).find(
(item) => item.name === "Brown Brim"
)
console.log(res)
Reference
Array.prototype.flatMap()
Maybe this is helpful?
const DATA= [
{id: 1,title:'Hats',routeName:'hats',
items:[{id: 1,name:"Brown Brim",price:25},
{id: 2,name: 'Blue Beanie',price: 18}]},
{id: 2,title: 'Sneakers',routeName: 'sneakers',
items: [{id: 3,name: 'Adidas NMD',price: 220},
{id: 4,name: 'Adidas Yeezy',price: 280}]}
];
console.log(DATA.map(D=>D.items.find(item=>item.name==='Brown Brim'))
.filter(e=>e))
The .map returns either an element matching your criterion or undefined, The chained .filter then removes all "falsy" elements, i. e. all the undefined ones.
As for the first question "loop Through this Array to find a specific item in Items Array"
given it is not sorted in any way, this can be done by iterating over the DATA array and search inside the items
If want to have access to the item from the outside of the 'forEach' scope you have to declare the variable outside
Regarding the second question, use the reduce function while iterating the array
NOTE: You can obviously combine both tasks as you already iterate through the array, so no need to do it twice. But to avoid confusion, I separated the logic.
Also, if you do choose to combine the tasks, using the reduce is not relevant, but very much like the answer to the first question, you can declare a buffer such as an array, and just copy items to it on the go (I'll leave out questions on performance for that matter)
const DATA = [
{
id: 1, title: 'Hats', routeName: 'hats',
items: [
{id: 1,name: 'Brown Brim',price: 25},
{id: 2,name: 'Blue Beanie',price: 18}
]
},
{
id: 2, title: 'Sneakers', routeName: 'sneakers',
items: [
{id: 3,name: 'Adidas NMD',price: 220},
{id: 4,name: 'Adidas Yeezy',price: 280}
]
}
];
//Question 1
//creating the object that will hold the item
//outside of the 'forEach' scope so we can use it later
let res = {};
const searchRes = DATA.forEach(entry => {
entry.items.forEach(item => {
if (item.name === 'Brown Brim')
//duplicating the item to a variable declared outside of this scope
res = { ...item
};
});
});
console.log(`Q1 - The item we found:`);
console.log(res);
// Question 2
// Merging all object inside the 'items' array using Reduce
const merged = DATA.reduce((acc, curr) =>
acc.concat(curr.items), []);
console.log(`Q2 - The merged array:`);
console.log(merged)

Return array of objects (from array of objects)

I have the following data and I want to return an array (of objects) of years that are distinct.
I tried the following function but I'm getting an array within an array.
const data = [{
id: 1,
name: "test1",
years: [{
id: 1,
name: "year1"
}, {
id: 2,
name: "year2"
}]
},
{
id: 2,
name: "test2",
years: [{
id: 1,
name: "year1"
}]
},
]
let years = data.map((s) => {
return s.years
})
let distinctYears = Array.from(new Set(years.map(c => c.id))).map(id => {
return {
id: id,
name: years.find(c => c.id === id).name,
}
})
console.log(distinctYears);
desired outcome:
[
{id: 1, name: "year1"},
{id: 2, name: "year2"}
]
Since s.years() is an array, and data.map() returns an array of the results, years is necessarily an array of arrays.
Instead of using .map(), use .reduce() to concatenate them.
const data = [{
id: 1,
name: "test1",
years: [{
id: 1,
name: "year1"
}, {
id: 2,
name: "year2"
}]
},
{
id: 2,
name: "test2",
years: [{
id: 1,
name: "year1"
}]
},
];
const years = data.reduce((a, {
years
}) => a.concat(years), []);
let distinctYears = Array.from(new Set(years.map(c => c.id))).map(id => {
return {
id: id,
name: years.find(c => c.id === id).name,
}
});
console.log(distinctYears);
There's so many ways you can go about doing this. Here's one, it's not a one-liner but its broken down to parts to help us understand whats going on.
Your dataset:
let data =
[
{
id: 1,
name: "test1",
years: [{id: 1, name: "year1"}, {id: 2, name: "year2"} ]
},
{
id: 2,
name: "test2",
years: [{id: 1, name: "year1"} ]
},
]
Use .flatMap() to create a one-level array with all items:
let allItems = data.flatMap((item) => {
return item.years.map((year) => {
return year
})
})
Getting distinct items:
let distinct = []
allItems.forEach((item) => {
let matchingItem = distinct.find((match) => match.id == item.id && match.name == item.name)
if(!matchingItem){
distinct.push(item)
}
})
In Practice:
let data = [{
id: 1,
name: "test1",
years: [{
id: 1,
name: "year1"
}, {
id: 2,
name: "year2"
}]
},
{
id: 2,
name: "test2",
years: [{
id: 1,
name: "year1"
}]
},
]
let allItems = data.flatMap((item) => {
return item.years.map((year) => {
return year
})
})
let distinct = []
allItems.forEach((item) => {
let matchingItem = distinct.find((match) => match.id == item.id && match.name == item.name)
if (!matchingItem) {
distinct.push(item)
}
})
console.log(distinct)

Reorder array of objects based on attribute

I have an array of objects, each with an 'id' and a 'name'. I'm retrieving an 'id' from the server and need to reorder the array starting from this id.
Example code:
var myList = [
{
id: 0,
name: 'Joe'
},
{
id: 1,
name: 'Sally'
},
{
id: 2,
name: 'Chris'
},
{
id: 3,
name: 'Tiffany'
},
{
id: 4,
name: 'Kerry'
}
];
Given an 'id' of 2, how can I reorder the array so my output is as follows:
var newList = [
{
id: 2,
name: 'Chris'
},
{
id: 3,
name: 'Tiffany'
},
{
id: 4,
name: 'Kerry'
},
{
id: 0,
name: 'Joe'
},
{
id: 1,
name: 'Sally'
}
];
Try this:
function orderList(list, id){
return list.slice(id).concat(list.slice(0,id));
}
Link to demo
You could slice the array at given index and return a new array using spread syntax.
const myList = [{id:0,name:'Joe'},{id:1,name:'Sally'},{id:2,name:'Chris'},{id:3,name:'Tiffany'},{id:4,name:'Kerry'}];
const slice = (arr, num) => [...arr.slice(num), ...arr.slice(0, num)];
console.log(slice(myList, 2));
myList.sort(function(a,b){
return a.id>2===b.id>2?a.id-b.id:b.id-a.id;
});
newList=myList;
http://jsbin.com/kenobunali/edit?console
You could splice the wanted part and use splice to insert it at the end of the array.
var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
id = 2;
myList.splice(myList.length, 0, myList.splice(0, myList.findIndex(o => o.id === id)));
console.log(myList);
using es6 spread syntax
var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
id = 2;
var index = myList.findIndex(o => o.id == id);
var arr = myList.splice(0, index);
var result = [...myList, ...arr];
console.log(result);

Merge two arrays into one with push()

I've got follow code:
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.push(list2);
I expect follow result:
list1:
0: Object (Zurich)
1: Object (London)
3: Object (New York)
4: Object (Dummy)
5: Object (Dummy2)
But I get this one:
list1:
0: Object (Zurich)
1: Object (London)
2: Object (New York)
3: Object (Items)
0: Object (Dummy)
1: Object (Dummy2)
How can I get my expectet result?
Thanks and cheers.
Beside Array#concat, you could use Array#push.apply for it
var list1 = { Items: [{ ID: 1, Name: "Zurich" }, { ID: 2, Name: "London" }, { ID: 3, Name: "New York" }] },
list2 = { Items: [{ ID: -1, Name: "Dummy" }, { ID: 0, Name: "Dummy2" }] };
[].push.apply(list1.Items, list2.Items);
console.log(list1);
The question was how to do this with push() not concat():
for (var i = 0; i < list2.Items.length; i++) {
list1.Items.push(list2.Items[i]);
}
Use the spread operator:
list1.Items.push(...list2.Items)
Spread is an ES2015 feature. Your target browsers or runtime may not support it yet, so check the compatibility table (or use a transpiler like babel).
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.Items = list1.Items.concat(list2.Items);
console.log(list1);
try with:
list2.items.forEach(function (item) {
list1.items.push(item)
})
You need to loop through each items in list2 and then fetch them to push into list1.. Below is the snippet using $.each
var list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
var list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
$(list2.Items).each(function(k,v){
list1.Items.push(v);
})
console.log(list1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources