I don't know how to write the title properly, pardon me on that.
Basically I have a list of array of object that's coming from a place, I need to map them together. How how with my code below I can't make it.
const person = [
{name:'hello',id:1},
{name:'javascript',id:2},
{name:'world',id:3}
];
const selected = [2,3];
const normalized = person.map((obj,i) => obj.id === selected[i] ? Object.assign({}, obj, {checked:true}) : obj);
console.log(normalized)
https://jsfiddle.net/q9g0kazx/1/
I need to add an extra property base on the selected array. Why above code doesn't work?
If I understand you correctly, just iterate through the array using forEach and add the property if needed.
const person = [
{name: 'hello', id: 1},
{name: 'javascript',id: 2},
{name: 'world',id: 3}
];
const selected = [2,3];
person.forEach(p => {
if (selected.includes(p.id)) {
p.checked = true;
}
});
console.log(person);
Or you can use map like this:
const person = [
{name: 'hello', id: 1},
{name: 'javascript',id: 2},
{name: 'world',id: 3}
];
const selected = [2,3];
person.map(p => {
if (selected.includes(p.id)) {
p.checked = true;
}
return p;
});
console.log(person);
Notice that you have to return the object (person in our case)
You can do this:
Check if the the id in the array is present in the selected array by:
selected.includes(obj.id)
So, includes returns true if the obj.id was present in the selected array. If present(yes) then your Object.assignpart of code executes.
The reason your code was not working was because your person array and selected array don't have same number of elements(count) and perhaps not in the order as well.
So person[0] id which is 1 doesn't match with selected[0] id which 2 and so on.
const person = [{
name: 'hello',
id: 1
},
{
name: 'javascript',
id: 2
},
{
name: 'world',
id: 3
}
];
const selected = [2, 3];
const normalized = person.map((obj, i) => selected.includes(obj.id) ? Object.assign({}, obj, {
checked: true
}) : obj);
console.log(normalized);
Related
I have an array of objects like this:
const myArr = [{id: 1, ...}, {id: 2, ...}, {id: 3, ...}];
and I have an object like this:
const myObj: {id: 2, someNewField};
I want to replace this new object for the one with the same ID in the original array, how can I do this?
I tried doing it like this:
const index = myArr.findIndex(item => item.id === myObj.id);
const filteredArr = myArr.filter(item => item.id !== myObj.id);
filteredArr.splice(index, 0, myObj);
It works but maybe there's a better way to do it
Instead of finding the index and filtering you could always use .map to return a new array.
const myObj = { id: 2, new: 1 };
const myArr = [{ id: 1 }, { id: 2 }, { id: 3 }];
const newArr = myArr.map(v => {
return v.id === myObj.id ? myObj : v;
});
It depends on what you would like to do if the item is not found in the array, as this will only replace.
By better if you mean faster method, here is one,
for(let i = 0;i<myArr.length; i++) {
if(myArr[i].id === myObj.id) {
myArr[i] = myObj;
break;
}
}
This is faster than your method because we are using for loop instead of .filter() or .findIndex() which is slower than regular for loop.
If you mean the most compact then you can do this,
myArr[myArr.findIndex(item => item.id === myObj.id)] = myObj;
Note that this approach will fail if there is no item with the given object key.
I'm trying to form the dictionary from tabs and data by iterating
I'm unable to form dictionary like structure and expected Output is mentioned
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [
{
node: {id: '1', name: 'first'}
},
{
node: {id: '2', name: 'second'}
},
{
node: {id: '3', name: 'third'}
},
]
}
}
let expectedOutput = {'first': '1','second':'2','third':'3'}
We have an object tabs. We can get key from this object using Object.keys(object_name). It will simply return us an array of key.
Object.keys(tabs) => [first, second,third]
data.accounts.members is also an array.We need to use array filter method to extract the node object from data.accounts.members array. Each item in array is an object. We can use object dot notation property to get value.
const filterarray = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
To read first value from array just simply use filterarray[0] index.
Reduce need initial value which is an empty object.We are appending data in this object.
We can simply add data in object using object[key] = value
Here key will be tabs key. tabs is also an object we need to read the value of that key and store result in object result[tabs[item]] = filterarray.node.id
Once reduce is over we will get result.
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [{
node: {
id: '1',
name: 'first'
}
},
{
node: {
id: '2',
name: 'second'
}
},
{
node: {
id: '3',
name: 'third'
}
},
]
}
}
const expectedOut =
Object.keys(tabs).reduce(
(result, item) => {
const ch = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
result[tabs[item]] = ch.node.id
return result
}, {})
console.log(expectedOut)
i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])
Let's say I have an array as follows:
types = ['Old', 'New', 'Template'];
I need to convert it into an array of objects that looks like this:
[
{
id: 1,
name: 'Old'
},
{
id: 2,
name: 'New'
},
{
id: 3,
name: 'Template'
}
]
You can use map to iterate over the original array and create new objects.
let types = ['Old', 'New', 'Template'];
let objects = types.map((value, index) => {
return {
id: index + 1,
name: value
};
})
You can check a working example here.
The solution of above problem is the map() method of JavaScript or Type Script.
map() method creates a new array with the results of calling
a provided function on every element in the calling array.
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*map() method creates a new array with the results of calling
a provided function on every element in the calling array.*/
let types = [
'Old',
'New',
'Template'
];
/*
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
*/
let Obj = types.map((value, i) => {
let data = {
id: i + 1,
name: value
};
return data;
});
console.log("Obj", Obj);
Please follow following links:
TypeScript
JS-Fiddle
We can achieve the solution of above problem by for loop :
let types = [
"One",
"Two",
"Three"
];
let arr = [];
for (let i = 0; i < types.length; i++){
let data = {
id: i + 1,
name: types[i]
};
arr.push(data);
}
console.log("data", arr);
is there any other way to write update an item in array of object other than below code?
const updateTodo = (list, updated) => {
const index = list.findIndex(item => item.id === update.id)
return [
...list.slice(0,index),
updated,
...list.slice(index+1)
]
}
Wait, is above function even working? https://jsbin.com/sifihocija/2/edit?js,console
The way you are doing it, is the right way to do it. However it is not working for you because in your case updated is an array and not an object and hence you only need to access the id of the first element of the array
const updateTodo = (list, updated) => {
const index = list.findIndex(item => return item.id === updated[0].id)
return [
...list.slice(0,index),
updated[0],
...list.slice(index+1)
]
}
JSBIN
However I prefer the library immutability-helper to perform any updates on the data you can do that like
import update from 'immutability-helper';
const updateTodo = (list, updated) => {
const index = list.findIndex(item => return item.id === updated[0].id)
return update(list, {
[index]: {
$set: updated[0];
}
})
}
One advantage of using immutabilty-helper is that its gives more control when the data is highly nested
You are doing to much. No need to manipulate the array if you know the index.
const items = [{id: 1, value: 1}, {id: 2, value: 2}, {id: 3, value: 3}];
items[2] = {id: 4, value: 4};
console.log(items); //last element changed
if you care about no side effects copy the array before
const items = [{id: 1, value: 1}, {id: 2, value: 2}, {id: 3, value: 3}];
const copy = items.slice();
copy[2] = {id: 4, value: 4};
return copy;
The simplest way to update(addition/deletion) an array is to use splice method.
it takes the first argument as the index, second as the no of elements you want to remove and next arguments for the addition.