This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I was calling a function and pass array of objects as first argument and second argument was object property of first argument but I don't know why map func doesn't accepting second argument property
Here code plz see it once
const myfunc = (arrObj, property) => {
const arr1 = arrObj.map(item => {
return item.property
}
return arr1:
}
const arrObj = [{
title: 'book',
body: 'hello'
},
{
title: 'cup',
body: 'hii'
}
];
// Func call
console.log(myfunc(arrObj, 'title'));
Use lowercase for const, return, console.
Return a value (an array, in this case) from your function that you can log.
Use item[property] to access the title property. There is no "property" key in those objects.
Make sure you close all of your parentheses.
function myfunc(arrObj, property) {
return arrObj.map(item => item[property]);
}
const arrObj=[{title:"book",body:"hello"},{title:"cup",body:"hii"}];
console.log(myfunc(arrObj, 'title'));
There are multiple errors in your code. First keywords like return,const,console are all case sensative. Secondly you are not returning from the function. Third since property is a variable you have to use square braces instead of dot
const myfunc = (arrObj, property) => {
return arrObj.map(item => {
return item[property]
})
}
const arrObj = [{
title: 'book',
body: 'hello'
},
{
title: 'cup',
body: 'hii'
}
];
// Func call
console.log(myfunc(arrObj, 'title'));
Related
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 2 years ago.
I feel like my problem is really easy to solve, but I cannot see it. I have simple thing to do, get myObject from another function and store this in my storage object. For this task I created storageHandler function. Everything works fine, but Object.assign is not reaching my 'ID' that I declared in this function earlier. This is weird because I don't know how to tell my function that 'ID' is variable, not a string. I just expect it to be {1212313: {...}} but instead it gives me {ID: {...}}.
Someone have any idea how to fix it?
let storage = {}
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com'
}
storageHandler = data => {
const {ID} = data;
Object.assign(storage, {ID: data})
console.log(storage)
}
storageHandler(myObject)
That's because in javascript this
a = { b: 1 };
is the same as
a = { "b": 1 };
You should change the Object.assign() for something like this
storage[ID] = data;
You should use the value of ID as key of object using [].
Object.assign(storage, {[ID]: data})
You are using string as a property name. Use computed property name like [ID] instead of ID. Computed property allows you to have an expression be computed as a property name on an object.
let storage = {};
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com',
};
storageHandler = (data) => {
const { ID } = data;
Object.assign(storage, { [ID]: data });
console.log(storage);
};
storageHandler(myObject);
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
I have object like picture below.
I want to use map() to retrieve the object like
{
"2643216":{pg:1,pt:1},
"1304681":{pg:1,pt:1}
}
Here is my code.
Object.keys(obj).map(function(x){
return {obj[x].number:{'pg':obj[x].pg,'pt':obj[x].pt}}
})
But errors may appear at the obj[x].number.
The debug errors notifies me the ignorance of the : (colon).
Is there mistake I make and any adjustment you can suggest-
or other way can retrieve the object I want?
Thank you.
this should do the job:
function groupByNumber(data) {
return Object
.keys(data)
.reduce(function(result, key) {
var value = data[key];
result[value.number] = { pt: value.pt, pg: value.pg };
return result;
}, {});
};
var data = {
'LKB_something': { number: 1, pg: 1, pt: 5 },
'LKB_something_else': { number: 2, pg: 1, pt: 5 },
'LKB_something_else_1': { number: 3, pg: 1, pt: 5 },
};
console.log('result', groupByNumber(data));
// ES-NEXT would let you be more coincise
const groupByNumber = data => Object.values(data).reduce(
(result, { number, ...rest }) => ({ ...result, [number]: rest }),
{},
);
For a dynamic key in a JavaScript object, you need square brackets to make a computed property name:
return { [obj[x].number]: { "pg": obj[x].pg, "pt": obj[x].pt }}
And your code could be simplified using Object.values and the implicit return of an arrow function, along with destructuring and shorthand property notation, like so:
Object.values(obj).map(({ number, pg, pt }) => ({ [number]: { pg, pt }}))
Note that the above returns an array of objects - if you want an object:
Object.values(obj).reduce((a, { number, pg, pt }) => ({ ...a, [number]: { pg, pt }}), {})
I have an user object - I want to generate test for each user property and check if it's the right type. However as typeof array is an object assertion fails on array properties with "AssertionError: expected [ 1 ] to be an object".
I have therefore checked if the property is an array and then generate special test for it. I'm wondering if this is the right approach? I have a feeling I'm misssing something obvious.
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
it(`should have property ${property}, type: array`, function () {
user.should.have.property(property);
});
} else {
it(`should have property ${property}, type: ${(typeof pureUser[property])}`, function () {
user.should.have.property(property);
user[property].should.be.a(typeof pureUser[property]);
});
}
});
pureUser is something like this:
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
User variable is defined elsewhere via got.js
change your test to be pureUser[property].should.be.an.Array or user[property].should.be.an.Array
forEach
The forEach() method calls a provided function once for each element in an array, in order.
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
console.log('Yes, it\'s an Array')
//it(`should have property ${property}, type: array`, function () {
// user.should.have.property(property);
//});
} else {
console.log('No, it\'s not an Array')
//it(`should have property ${property}, type: ${(typeof property)}`, function () {
//user.should.have.property(property);
// user[property].should.be.a(typeof pureUser[property]);
//});
}
});
When you use forEach on pureUser, the parameter will be the objects properties, like username, id, etc
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
console.log(property);
});
You can also access the array in your forEach function.
arr.forEach(item, index, arr)
This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);
let schools = [
{ name: "Yorktown"},
{ name: "Stratford" },
{ name: "Washington & Lee"},
{ name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
const editName = (oldName, name, arr) =>
arr.map(item => {
if (item.name === oldName) {
// what is happening below!?
return {
...item,
name
}
} else {
return item
}
})
first of all, i'm sorry if this question might be easy for you, but i'm having trouble understanding how the return statement of the snippet works and would really appreciate help.
return { ...item, name }
So i would expect updatedSchool to be (even though it's invalid syntax):
[
{name: "Yorktown"},
{ name: "Yorktown", "HB Woodlawn"},
{ name: "Washington & Lee"},
{ name: "Wakefield"}
]
why does it produce { name: "HB Woodlawn" }?
Simply desugar expression step by step
{...item, name }
First {name} is shortcut for {name: name}
Then {...obj} is the same as Object.assign({}, obj)
Combining both gives Object.assign({}, obj, {name: name})
Given obj = {name: 'Stratford'} has only one property name it will simply create new object and replace name with a new one.
You can read about Object.assign here
return { // the spread operator assigns existing properties of item
...item, // to the new returned object
name // similar to return Object.assign(item, {name: name})
}
The rest parameter can work on objects as well as arrays in browsers that support it. If you want to understand the code, it's best to walk through it.
editSchools is a function that takes an oldName, a name, and an array. It returns the result of the mapping from array to a new array. Each element in the new array is determined by the callback function that map executes. If the item's name property is equal to the oldName, then a new object is created which will take its place, {...item, name}. This is where the confusion lies.
It does something weird. The new object recieves all the keys of the item object, and then it will define (or redefine) the name property to the value of name provided to editSchools.
So in essence, this code finds the objects that have a name key whose value is oldName and replaces it with an identical new object with a changed name property to the new name value.