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);
Related
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);
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' } ]
for example - lets say I have the array -
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
I want to run once on that array and at the end of that run to have two arrays -
const arrayOne = ["first", "second"];
const arrayTwo = [1,2];
to get the first one is easy, but getting both at once?
I remember there was a way to do it but couldn't find it..
I'd appreciate any help!
Any looping logic will help
Array.reduce implementation will be like below
const array = [{ name: "first", val: 1 }, { name: "second", val: 2 }];
const [arrayOne, arrayTwo] = array.reduce((acc, curr) => {
const { name, val } = curr;
acc[0].push(name);
acc[1].push(val);
return acc;
}, [[], []]);
console.log(arrayOne, arrayTwo);
The function extractArrays is general-purpose and can be used in other cases as well.
function extractArrays(arr) {
const result = {};
for (obj of arr) {
for (key in obj) {
result[key] = (result[key] || []).concat([obj[key]]);
}
}
return result;
}
const array = [{name: "first", val: 1}, {name: "second", val: 2}];
const result = extractArrays(array);
const arrayOne = result.name;
const arrayTwo = result.val;
console.log(`arrayOne=${arrayOne}`);
console.log(`arrayTwo=${arrayTwo}`);
You can use Array.reduce to achieve this:
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
const result = array.reduce((res, item) => {
res[0].push(item.name)
res[1].push(item.val)
return res
}, [[], []])
console.log(result)
thanks everyone!
but I think that the easiest, most readable code would be something like -
const itemArray = [], valArray = [];
data.map(({name, val})=> {
if(name) nameArray.push(name);
if(val) valArray.push(val);
})
because basically in 4 lines of code it's finished
thanks again everyone!
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
const keys = [];
const values = [];
array.forEach(item=>{
keys.push(item.name);
values.push(item.val);
})
console.log(keys, values)
Use the Array.map function:
const array = [ { name: 'first', val: 1 }, { name: 'second', val: 2 } ]
let names = array.map(item => item.name)
let vals = array.map(item => item.val)
console.log(names)
console.log(vals)
The map function calls a callback function you provide on each element and constructs a new array from the results of that function.
If you are not familiar with arrow functions like:
item => item.name
... it is a short form for:
function (item) {
return item.name
}
You could even do it in one line:
let [ names, vals ] = [ array.map(item => item.name), array.map(item => item.val) ]
Is there any way to convert a list of objects into a new list where the properties are now values. I have tried to use Object.keys() and Object.values() to make two separate lists and then trying to combine them, without much success.
Example:
I want to turn:
[{ip: 123, name: "bob"}]
into:
[{property: "ip", value: 123}, {property: "name", value: "bob"}]
How do I solve this problem?
I would simply do a for loop, go through the array and then push these new objects in a new array.
The following code should solve your issue:
const array1 = [{ ip: 123, name: 'bob' }];
let newArray;
for (let i = 0; i < array1.length; i++) {
newArray.push({
property: 'ip',
value: array1[i].value
});
newArray.push({
property: 'name',
value: array1[i].name
});
}
You could use upcoming Array#flatMap and take the entries of the object.
var data = [{ ip: 123, name: "bob" }],
result = data.flatMap(o => Object.entries(o).map(([property, value]) => ({ property, value })));
console.log(result);
Traditional approach with Array#reduce.
var data = [{ ip: 123, name: "bob" }],
result = data.reduce((r, o) => [
...r,
...Object.entries(o).map(([property, value]) => ({ property, value }))
], []);
console.log(result);
I have the following array, which has an object holding nested arrays that in turn have objects of their own:
var list = [{
one: [{key: 1, value: 'eng1'}, {key: 2, value: 'eng2'}],
two: [{key: 1, value: 'esp1'}, {key: 2, value: 'esp2'}]
}];
I want to group the data above by the key property inside the objects of the nested arrays. The following is the desired structure:
var grouped = [
{
key: 1,
group: {
one: {
value: 'eng1'
},
two: {
value: 'esp1'
}
}
},
{
key: 2,
group: {
one: {
value: 'eng2'
},
two: {
value: 'esp2'
}
}
}
]
I have tried so many ways to achieve the above structure but to no avail. I have tried using reduce but that was mainly applicable if the objects were not deeply nested. My problem is the fact that the arrays are nested inside the objects and the key is embedded in those objects. Your help would be greatly appreciated.
The requirement is to not use any library such as underscore or lodash. I have to get this working with plain JS.
You can use multiple forEach loops because of your data structure and add to new array.
var list = [{
one: [{key: 1, value: 'eng1'}, {key: 2, value: 'eng2'}],
two: [{key: 1, value: 'esp1'}, {key: 2, value: 'esp2'}]
}];
var grouped = [];
list.forEach(function(e) {
Object.keys(e).forEach(function(k) {
var that = this;
e[k].forEach(function(a) {
if(!that[a.key]) grouped.push(that[a.key] = {key: a.key, group: {}})
Object.assign(that[a.key].group, {[k]: {value: a.value}})
})
}, {})
})
console.log(grouped)
You may try for this:
var list = [{
one: [{key: 1, value: 'eng1'}, {key: 2, value: 'eng2'}],
two: [{key: 1, value: 'esp1'}, {key: 2, value: 'esp2'}]
}];
var grouped = [];
list.forEach(function(e) {
Object.keys(e).forEach(function(k) {
var that = this;
e[k].forEach(function(a) {
if(!that[a.key]) grouped.push(that[a.key] = {key: a.key, group: {}})
Object.assign(that[a.key].group, {[k]: {value: a.value}})
})
}, {})
})
console.log(grouped)