How to replace array of object property name in javascript - javascript

I need to replace array of object in javascript. Here is my data variable and I want to update data variable
const data = [{name: "poran", id: "22"}];
Expected value:
data = [{value: "poran", age: "22"}];
How can I replace array of object?

You can create a new array with the use of .map() and some Object Destructuring:
const data = [{name:"poran",id:"22"}];
const result = data.map(({ name:value , id:age }) => ({value, age}));
console.log(result);

You can use a .forEach() loop over the array:
data.forEach((obj) {
obj.value = obj.name;
obj.age = obj.id;
delete obj.name;
delete obj.id;
});
It's a little simpler if you just make a new array with .map(), but if you need to keep the old objects because there are lots of other properties, this would probably be a little less messy.

try this:
const data = [{name:"poran",id:"22"}]
const rst = data.map(res=>({value: res.name, age: res.id}));
console.log(rst)

Related

Use lodash to filter array of objects and check if object property value exists in another Array

I am trying to achieve the following task with lodash or pure JS.
I have an Array of Objects which I filter by a given property value
let res = _.filter(array, {obj.property: "somevalue"}
Now I have another Array like so [val1, val2,val3] which I want the filtered array properties to compare with like so.
let res = _.filter(array, {obj.property1: "somevalue", obj.property2: existsInOtherArray}
You can use a set and the filter method of array like:
const array = [
{property1: 'somevalue'},
{property1: 'somevalue', property2: 'val2'}
]
const set = new Set(['val1', 'val2', 'val3'])
const res = array.filter(obj => obj.property1 === 'somevalue'
&& set.has(obj.property2))
console.log(res)

Converting an object to array

I have a object like this
users = {
user1:{name: bob,
age:23},
user2:{name:rob,
age:24},
user3:{name:jay,
age:30}}
How to convert this object into an array like [user1:{name: bob,age:23},user2{name:rob,age:24},user3:{name:jay,
age:30}]
Simple, map the Object.keys array of your object to the array you want. I added in the object key as the "id" field.
const users = {
user1:{name: 'bob',
age:23},
user2:{name:'rob',
age:24},
user3:{name:'jay',
age:30}};
const arr = Object.keys(users).map(key => ({id: key, ...users[key]}));
console.log(arr);
the map solution is more up to date but sometimes old vanilla js is easier to understand
const users = {user1:{name:'bob',age:23},user2:{name:'rob',age:24},user3:{name:'jay',age:30}};
var myArray=[];
for(let i =1;i<4;i++){
var user={['user'+i]:users['user'+i]} //create your object
myArray.push(user); //add it to array
}
console.log(myArray[0]['user1']) // remember arrays are indexed []
console.log(myArray[1]['user2'])
console.log(myArray[2]['user3'])
console.log(myArray);
.as-console-wrapper{min-height:100%;})

How to get the name from the array in javascript?

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.
I am trying to loop by using forEach.
let Person = {
name: ['Sam']
}
let handler = Object.keys(Person)
handler.forEach(function(element){
console.log(element)
})
Object.keys() only gives you keys
Use Object.entries() if you want key and value
Use Object.values() if you only want values
let Person = {
name: ['Sam']
}
for (const fn of ["values", "keys", "entries"]) {
console.log(`Using: Object.${fn}()`);
for (const v of Object[fn](Person)) {
console.log(v);
}
}
Instead of Object.keys use Object.values
If you know in advance that your name array is located under the key name, then access it directly
const person = { name: ['Sam'] };
console.log(person.name);
console.log(person.name[0]);
Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:
const person = { name: ['Sam'], anotherProp: 'hello' };
console.log(Object.values(person));
Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.
let Person = {
name: ['Sam',"Bob","Alice"]
}
let count = Person.name.length;
for(let i = 0; i<count; i++){
console.log( Person.name[i])
}
If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.
Object.keys(obj).forEach(key => obj[key]);
let Person = {
name: ['Sam']
}
Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`));

Finding the object key with the value inside the array?

I know Some people might find this very easy. But It seems to be very difficult to start. If i have array i could have easily done with filter.
Lets say i have this object
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
Now if I have atribute = "gender" How can i find the key family.
if I have atribute = "livingType" Then i need House;
Any Javascript pro here?
Thanks in advance
You could get the keys and find with includes.
Methods:
Object.keys for getting own keys from an object,
Array#find for finding an item with a callback,
Array#includes, this checks if an item exists in an array.
const
mapData = { family: ["gender", "ethnics"], house: ["wardNumber", "livingType"] },
attribute = "gender",
key = Object
.keys(mapData)
.find(k => mapData[k].includes(attribute));
console.log(key);
You can use Object.keys() and filter()
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const findKey = (obj,attr) => Object.keys(obj).filter(k => obj[k].includes(attr))[0]
console.log(findKey(mapData,"gender"))
console.log(findKey(mapData,"livingType"))
You can do it with Object.entries(), Array.find(), Array.includes() and Array.shift().
If the value is not found, this will return undefined.
const data = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const getKey = val =>
(Object.entries(data).find(([k, v]) => v.includes(val)) || []).shift();
console.log(getKey('gender'));
console.log(getKey('livingType'));
console.log(getKey('non-existing-value'));

Updating object properties and adding them in a new Arr with Reduce Javascript

I am trying to use reduce within addKeyAndValue function on an array of objects with properties of key-value pairs, add within each object a new key-value pair and return that on a new array. The addKeyAndValue func receives three arguments the arr, the key and the value to be added together within each object in the array. I then use push within Reduce callback to push the objects in the array to the new array in the accumulator with the updated new key and value using the bracket notation.
var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}]
function addKeyAndValue(arr, key, value){
return arr.reduce(function(acc, nextValue, idx){
console.log(next);
acc.push(nextValue[key] = value);
return acc;
},[]);
}
and the expected result should be:
addKeyAndValue(arr, 'title', 'Instructor') //
[
{title: 'Instructor', name: 'Alonso'},
{title: 'Instructor', name: 'James'},
{title: 'Instructor', name: 'Chris'},
{title: 'Instructor', name: 'Steve'}
]
however, the results that I get in my Chrome dev console is:
(4) ["Instructor", "Instructor", "Instructor", "Instructor"]
0:"Instructor"
1:"Instructor"
2:"Instructor"
3:"Instructor"
length:4
__proto__:Array(0)
I am wondering why is the Value passed through nextValue[key] overriding the whole object and returning just as a string. When I try to just push the existing objects in the new array it works fine but when pushing the nextValue[key] it turns undefined and when doing the above nextValue[key] = value it overrides the objects resulting into a new array with just instructor strings. I am a bit confused since I was expecting a different result.
Using the bracket notations nextValue[key] on nextValue which is each object within the array being iterated by the callback in the reduce method I thought that would add a new key property in this case "title" with the assigned value of "instructor".
Any help would be appreciated, Thanks :).
Your push argument only results in the value being pushed, not the object. You can solve this with the comma operator if your really want this in one expression:
acc.push((nextValue[key] = value, nextValue));
But it may be more readable if you do it separately:
nextValue[key] = value;
acc.push(nextValue);
You are pushing the result of the assignment into the array, instead of the object.
Since the result nextValue[key] = value is value. Using acc.push(nextValue[key] = value); is like doing acc.push(value).
Since you want to update each object, use Array#map to iterate the array. Clone each object (to prevent mutating the original objects) using Object#assign, and add the property:
var arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
function addKeyAndValue(arr, key, value){
return arr.map(function(obj){
var clone = Object.assign({}, obj);
clone[key] = value;
return clone;
});
}
var result = addKeyAndValue(arr, 'title', 'Instructor');
console.log(result);
The ES6 version
const arr = [{name: 'Alonso'}, {name: 'James'}, {name: 'Chris'}, {name: 'Steve'}];
function addKeyAndValue(arr, key, value){
return arr.map((obj) => Object.assign({ [key]: value }, obj));
}
const result = addKeyAndValue(arr, 'title', 'Instructor');
console.log(result);

Categories