how to access and assign new value in array/object in lodash - javascript

I am looking for simple easy way to assign new value through lodash. See the blow example. I only want to reassign value of first element of object of first element of arr array.
const arr = [
{
a: 'apple',
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
const newArr = arr;
const ele = ._first(newArr);// picked first element
ele['a'] = 'dog';
this is what I expect to see
console.log(newArr);
// [
{
a: 'dog', //<--- updated
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
thank you ahead!

Why you cannot just use simple JS without lodash?
const arr = [
{
a: 'apple',
b: 'banana',
c: 'cat'
},
{
a: 'apple-1',
b: 'banana-2',
c: 'cat-3'
}
];
const newArr = arr;
newArr[0].a = 'dog'
console.log(arr)

Related

How to get all values of a specific key in array of objects?

I have array of objects like this
const object1 = {
a: 'somestring',
b: 42,
c: false
};
const object2 = {
a: 'somestring2',
b: 42,
c: false
};
const object3 = {
a: 'somestring3',
b: 42,
c: false
};
const arr = [object1,object2,object3]
i want to get all the values of 'a' key.
so result be
['somestring','somestring2','somestring3']
I tried Object.values() but it gets me all values of all keys, which is not the desired output.
Just use map() function:
const arr = [object1,object2,object3].map(({a}) => (a))
An example:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
const object2 = {
a: 'somestring2',
b: 42,
c: false
};
const object3 = {
a: 'somestring3',
b: 42,
c: false
};
const arr = [object1,object2,object3].map(({a}) => (a))
console.log(arr)
Have you tried const arr = [object1.a, object2.a, object3.a]? That might work

array of objects manipulation in js

I have an array of object as below.
data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },]
From above, I need to get array of array as below.
[ [{a: 'amb',b: [1], c: 'red'}, {a: 'amb',b: [2], c: 'orange'}],
[{a: 'bfg',b: [3], c: 'red'}, {a: 'bfg',b: [4], c: 'orange'}]
]
My attempt is as below.
let arrInner: Array<any> = []
let arrOuter: Array<Array<any>> = []
_.forEach(data, (item, i) => {
//create two objects redObj and orangeObj
redObj = {
a: item.col[0].toString(),
b: [item.col[1] as number],
c: 'red'
}
orangeObj = {
a: item.col[0].toString(),
b: [item.col[2] as number],
c: 'orange'
}
//put those two objects to array
arrInner.push(redObj)
arrInner.push(orangeObj)
//assign that array to another array
arrOuter[i] = arrInner
})
But when I print the arrOuter, it is not my expected output. Where I was wrong and how can I fix this?
You need to create a new arrInner each time through the forEach loop. Then push that onto arrOuter.
let arrOuter: Array <Array <any>> = []
_.forEach(data, (item, i) => {
//create two objects redObj and orangeObj
redObj = {
a: item.col[0].toString(),
b: [item.col[1] as number],
c: 'red'
}
orangeObj = {
a: item.col[0].toString(),
b: [item.col[2] as number],
c: 'orange'
}
//put those two objects to array
let arrInner = [redObj, orangeObj]
//assign that array to another array
arrOuter.push(arrInner)
})

Get an element object of an array from a key name

I'm parsing a csv fils to json with node-csvtojson and I got a JSONarray with the following code
csv({delimiter: ';'}).fromFile(path).then((jsonObj)=>{
data = jsonObj;
console.log(jsonObj);
})
with a csv like
a,b,c
A,B,C
1,2,3
1,B,C
I have got
[
{
a: A,
b: B,
c: C,
},
{
a: 1,
b: 2,
c: 3,
},
{
a: 1,
b: B,
c: C
}
]
But I want to find every object who has the element a === 1 and I want to have all the content of the object,
like this:
{
a: 1,
b: 2,
c: 3,
},
{
a: 1,
b: B,
c: C,
}
But I 'm struggling to do that, I have tried with array.filter but without success then I have tried to do this with array.map but I got lost on how to do.
Do you have any idea on or I could do that ?
Than you
Use Array.filter like so:
const data = [{
a: 'A',
b: 'B',
c: 'C',
},
{
a: 1,
b: 2,
c: 3,
},
{
a: 1,
b: 'B',
c: 'C'
}
];
console.log(data.filter(({ a }) => a == 1));
If you want this to work with old browsers, here's an ES5-compliant version:
var data = [{
a: 'A',
b: 'B',
c: 'C',
},
{
a: 1,
b: 2,
c: 3,
},
{
a: 1,
b: 'B',
c: 'C'
}
];
console.log(data.filter(function(obj) {
return obj.a == 1
}));
Simple use Array.filter to filter through the object array and select the one having property a === 1
var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const filteredArr = arr.filter(obj => obj.a === 1);
console.log(filteredArr);
Using Array.reduce you can do the same thing:
var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const redArr = arr.reduce((acc, obj) => {
return acc = obj.a === 1 ? acc.concat(obj) : acc;
}, []);
console.log(redArr);
Using Array.map for this problem is not the right approach, although it is possible:
var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const mapArr = arr.map(obj => obj.a === 1 ? obj : undefined).filter(obj => obj); //hack to remove undefined elements
console.log(mapArr);
console.log([{
a: 'A',
b: 'B',
c: 'C',
},
{
a: 1,
b: 2,
c: 3,
},
{
a: 1,
b: 'B',
c: 'C'
}
].filter(o => o.a === 1))
Try this :
var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
var res = arr.filter(obj => obj.a === 1);
console.log(res);

How to map more than one property from an array of objects [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
I have an array of Object as follows:
var obj = [
{a: 1, b: 5, c: 9},
{a: 2, b: 6, c: 10},
{a: 3, b: 7, c: 11},
{a: 4, b: 8, c: 12}
];
I know about how to get single object using Array.map() like this.
var result = obj.map(x=>x.a)
This will give me following result
[1, 2, 3, 4]
But I want result like follows:
[
{a: 1, b: 5},
{a: 2, b: 6},
{a: 3, b: 7},
{a: 4, b: 8}
]
In short, from an array of objects I want to select only a few fields (more than one).
How can I do that?
You can use .map() with Object Destructuring:
let data = [
{a:1,b:5,c:9}, {a:2,b:6,c:10},
{a:3,b:7,c:11}, {a:4,b:8,c:12}
];
let result = data.map(({ a, b }) => ({a, b}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If, as in your example, you want to exclude a particular property or few, you can use destructuring and use rest properties to create an object with only the properties you want:
var obj = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
const mapped = obj.map(({ c, ...rest }) => rest);
console.log(mapped);
If you want to include properties, simply extract them from the .map callback:
var obj = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
const mapped = obj.map(({ a, b }) => ({ a, b }));
console.log(mapped);
Use map():
var data = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let modified = data.map(obj => ({a: obj.a, b: obj.b}))
console.log(modified);
Or if you prefer destructuring:
var data = [
{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let modified = data.map(({ a, b }) => ({a, b}));
console.log(modified);
var obj = [
{a: 1, b: 5, c: 9},
{a: 2, b: 6, c: 10},
{a: 3, b: 7, c: 11},
{a: 4, b: 8, c: 12}
];
var result = obj.map(e => ({a:e.a , b:e.b}));
console.log(result)
You can return a custom object with required properties using map()
var obj = [{a:1,b:5,c:9},
{a:2,b:6,c:10},
{a:3,b:7,c:11},
{a:4,b:8,c:12}
];
let op = obj.map(e => {
return { a:e.a, b: e.b };
})
console.log(op);
In your solution for producing [1,2,3,4], x.a isn’t some micro-syntax, it’s actually a full-fledged JavaScript expression. So you can just replace it with the JavaScript for creating a new object with the properties you want.
var result = obj.map(x=>{a: x.a, b: x.b});
... almost. The additional complication is that a { after a => is interpreted as the beginning of a function body, not the beginning of an object literal. You can avoid this by just wrapping the object literal in otherwise-noop parenthesis.
var result = obj.map(x=>({a: x.a, b: x.b}));
You can make your own custom function for this, and pass it a set of properties which you want to extract. :
var array = [{a:1,b:5,c:9}, {a:2,b:6,c:10}, {a:3,b:7,c:11}, {a:4,b:8,c:12} ];
function extractProperties(arr, properties){
return arr.map((obj)=> Object.keys(obj).reduce((acc,key)=>{
if(properties.has(key))
acc[key] = obj[key];
return acc;
},{}));
}
let set = new Set(["a","b"]);
let result = extractProperties(array, set);
console.log(result);
set.add("c");
console.log("**************result2**********")
let result2 = extractProperties(array, set);
console.log(result2);

How to get value from index property in javascript?

Here is my code:
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
value[dealId] = array2.push(obj[property]);
}
console.log(value)
The output of this is
Object { 123: 3 }
But I want and this is what I was expecting.
Object { 123: [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}] }
Why am I getting 3 instead of an array? How to get the array?
Array.prototype.push returns the new length of the array, not the array itself. Your loop assigns the values 1, 2 and 3 to the same value[dealId].
Instead, you can move the assignment outside the loop:
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
Or you can simply use Object.values:
value[dealId] = Object.values(obj);
But note that this does not list inherited properties.
Why not build a new object with a single key and the given array as value?
For the object use a computed property name.
const
array = [{ a: 'abc', b: 'cd' }, { a: 'abc', b: 'xyz' }, { a: 'abc', b: 'mno' }],
key = 123,
object = { [key]: array };
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you need to add into aaray first then create the object
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc', b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value);
const array1 = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let obj = array1.reduce(function(result, item, index){
result[index] = item
return result;
}, {});
let dealId = 123;
let value = {};
let array2 = [];
for (var property in obj) {
array2.push(obj[property]);
}
value[dealId] = array2;
console.log(value)
Assign your new obj property (id) the requested array:
let arr = [{a: 'abc', b: 'cd'}, {a: 'abc', b: 'xyz'}, {a: 'abc',
b: 'mno'}];
let newObj = {};
let id = 123;
newObj[id] = arr;
console.log(newObj);

Categories

Resources