I have one object and one is an array of objects like :
let obj = {
id:'1',
v1: '4',
v2: '2',
v3: '3',
}
const arr= [{key:1, value: 'v1'},{key:2, value:'v2'}]
here in the array of objects, I want concat values like this using key and value of obj
arr= [{key:1, value: 'v1:4'},{key:2, value:'v2:2'}]
basically, I just want to update the text value like this using object and an array of object
Note - every time I'm getting a new object so how can I achieve this in loop
You can use map().
let obj = {
id: "1",
v1: "4",
v2: "2",
v3: "3",
};
const arr = [
{ key: 1, value: "v1" },
{ key: 2, value: "v2" },
];
const result = arr.map(({ key, value }) => ({ key, value: `${value}:${obj[value]}` }));
console.log(result)
This solution uses object destructuring to get the key and value and looks up the values in the object using obj[value].
Try this :
let obj = {
id: '1',
v1: '4',
v2: '2',
v3: '3',
};
const arr= [{key:1, value: 'v1'},{key:2, value:'v2'}];
arr.forEach((arrayObj, index) => {
arr[index].value = Object.keys(obj).includes(arrayObj.value) ? `${arrayObj.value}:${obj[arrayObj.value]}` : arrayObj.value
});
console.log(arr);
Related
I'm receiving from backend side object which is formulated like:
[
{value: 'FIRST', AvailableValues[{code: "one"},{code: "two"}]},
{value: 'SECOND', AvailableValues[{code: "one"},{code: "two"}]
]
My question is how to map through this object to create pairs like
[{value: "FIRST", code:"one"},
{value: "FIRST", code:"two"},
{value: "SECOND", code:"one"},
{value: "SECOND", code:"two"}]
Thanks
I tried combination of javascript predefined methods like double map, keyed search and so on, but it resulted with errors
use reduce function
Also, your initial data should be an array because if it's a object, then it should contains key with values
const list = [
{value: 'FIRST', AvailableValues:[{code: "one"},{code: "two"}]},
{value: 'SECOND', AvailableValues:[{code: "one"},{code: "two"}]}
]
const result = list.reduce((acc,item) => {
const res = item.AvailableValues.map(i => ({value: item.value, code: i.code}))
return [...acc,...res]
}, [])
console.log(result)
Try something like this, Assuming that you receiving array of object from backend
let result = [];
yourObject.forEach((x)=>{
x.AvailableValues.map((innerItem)=>{
result.push({value:x.value, code : innerItem.code})
});
})
console.log(result)
The other answers here gets the job done. For completion here is an approach using flatMap combined with an inner map
const data =[
{value: 'FIRST', AvailableValues:[{code: "one"},{code: "two"}]},
{value: 'SECOND', AvailableValues:[{code: "one"},{code: "two"}]}
]
const res = data.flatMap(({value,AvailableValues}) => AvailableValues.map(({code}) => ({value,code})))
console.log(res)
var response = [{
value: 'FIRST', AvailableValues: [{ code: "one" }, { code: "two" }]},{
value: 'SECOND', AvailableValues: [{ code: "one" }, { code: "two" }]}
];
var output = [];
response.forEach(function(o) {
o.AvailableValues.forEach(function(oo) {
var t = {
value: o.value,
code: oo.code
};
output.push(t);
})
});
console.log(output);
Say I have an array of objects:
const myArr = [
{name: 'one'},
{name: 'two'}
]
If I wanted to use this array of object as a base and add a custom property to the objects for each use case I might have, could I assign the array to a new variable and also change the contents of its objects at the same time?
I know this can be done in 2 steps, but I'm wondering if it's possible to do it all at once?
For example:
const copyArr = myArr;
copyArr.forEach(obj => obj.newProp = 'some-new-prop');
This would now be
[
{name: 'one', newProp: 'some-new-prop'},
{name: 'two', newProp: 'some-new-prop'}
]
You can use Array.map to iterate over each item and modify them.
Note that map will not modify your original array and therefore is immutable.
const myArr = [{ name: "one" }, { name: "two" }];
const copyArr = myArr.map((item) => ({
...item,
newProps: "some-new-prop",
}));
// [ { name: 'one', newProps: 'some-new-prop' },
// { name: 'two', newProps: 'some-new-prop' } ]
I have an array of object - like this -
test: [
{
id:'1',
name:'A'
},
{
id:'2',
name:'B'
},
]
Suppose I have a value 2 that exists in object Test as id. I want to get whole object from array if id value exists in whole array
input - 2,
expected output - {id:'2' , name:'B'}
How Can we get it ? is it any possible solution ?
Simply use find-
const val = [
{
id: '1',
name: 'A',
},
{
id: '2',
name: 'B',
},
];
const res = val.find(obj => obj.id === '2');
console.log(res);
There can be multiple ways to do this. Here is how I did it.
let test = [
{
id: '1',
name: 'A'
},
{
id: '2',
name: 'B'
}
];
let result = (param) => test.filter(el => {
return el.id == param
});
console.log(result(2))
This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
How to filter an array of objects with a condition and return only specific properties of filtered objects?
I know we can use filter followed by map to achieve this. But I am looking for more simple solution.
For ex:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
Suppose if I want only ids of name "lala".
Output should be,
[{id: 1}, {id: 3}]
The next simplest would be reduce
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
console.log(
arr.reduce((values, value) =>
{
if (value.name === 'lala') values.push({ id: value.id });
return values;
}, [])
);
You can simply use Array.prototype.reduce to combine both mapping and filtering in the same operation. If you want to make it super concise, you can use object destructuring in the second argument of the reduce callback:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
let filteredMappedArr = arr.reduce((acc, { name, id }) => {
if (name === 'lala')
acc.push({ id });
return acc;
}, []);
console.log(filteredMappedArr);
filter followed by map is probably the most readable solution, but if you're looking to do it all in one step, you're looking at the classic for loop or using reduce.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can do it by using filter and map;
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let res = arr.filter(item => item.id % 2 === 1).map(item => ({id: item.id}))
console.log(res);
You could take Array#flatMap and return either a new obejct or an empty array which has no value for flattening.
let array = [{ name: "lala", id: 1 }, { name: "coco", id: 2 }, { name: "lala", id: 3 }],
result = array.flatMap(({ id, name }) => name === 'lala' ? [{ id }] : []);
console.log(result);
using .filter() and .map() functions:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let newArr = arr.filter((elm) => (elm.name === 'lala')).map( (elm) => {return {id:elm.id}});
console.log(newArr);
let arr = [
{ name: "lala", id: 1 },
{ name: "coco", id: 2 },
{ name: "lala", id: 3 },
];
let a = [];
arr.filter(({ name, id }) => {
if (name === "lala") {
a.push({ id });
}
});
console.log(a);
with filter we check for the condition where name matches 'lala' if yes then we push id to new array...that's simple
I have an array of objects (objList) that each has "id" property.
I have an array of strings (idsToRemove), representing IDs of the objects to remove from objList.
I find some solution but I fear it's slow, especially with the large list of objects with lots of properties.
Is there more efficient way to do this?
var idsToRemove = ["3", "1"];
var objList = [{
id: "1",
name: "aaa"
},
{
id: "2",
name: "bbb"
},
{
id: "3",
name: "ccc"
}
];
for (var i = 0, len = idsToRemove.length; i < len; i++) {
objList = objList.filter(o => o.id != idsToRemove[i]);
}
console.log(objList);
Turn the idsToRemove into a Set so that you can use Set.prototype.has (an O(1) operation), and .filter the objList just once, so that the overall complexity is O(n) (and you only iterate over the possibly-huge objList once):
var idsToRemove = ["3", "1"];
var objList = [{
id: "1",
name: "aaa"
},
{
id: "2",
name: "bbb"
},
{
id: "3",
name: "ccc"
}
];
const set = new Set(idsToRemove);
const filtered = objList.filter(({ id }) => !set.has(id));
console.log(filtered);
Note that Array.prototype.includes and Array.prototype.indexOf operations are O(N), not O(1), so if you use them instead of a Set, they may take significantly longer.
You can use Array.includes which check if the given string exists in the given array and combine it with an Array.filter.
const idsToRemove = ['3', '1'];
const objList = [{
id: '1',
name: 'aaa',
},
{
id: '2',
name: 'bbb',
},
{
id: '3',
name: 'ccc',
},
];
const filteredObjList = objList.filter(x => !idsToRemove.includes(x.id));
console.log(filteredObjList);
You don't need two nested iterators if you use a built-in lookup function
objList = objList.filter(o => idsToRemove.indexOf(o.id) < 0);
Documentation:
Array.prototype.indexOf()
Array.prototype.includes()
Simply use Array.filter()
const idsToRemove = ['3', '1'];
const objList = [{
id: '1',
name: 'aaa',
},
{
id: '2',
name: 'bbb',
},
{
id: '3',
name: 'ccc',
}
];
const res = objList.filter(value => !idsToRemove.includes(value.id));
console.log("result",res);