How to populate Object with key: value in JS? [duplicate] - javascript

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 10 months ago.
I have the following function. The current output is name: "foo" surname: "bar"
How can I push my console log data to my payload
{
name: "foo",
surname: "bar
}
so the output becomes:
const ProcessHTML = (rawHtml, elements) => {
const $ = cheerio.load(rawHtml);
let payload = {}
for (const data in elements) {
let currentElement = $(elements[data]);
let prettify = pretty(currentElement.html())
console.log(`${data}: ${prettify}`)
}
return payload
};

I can't understand if you are trying to output a single value in console or the full payload object, but I think is something like that:
const ProcessHTML = (rawHtml, elements) => {
const $ = cheerio.load(rawHtml);
let payload = {}
elements.forEach( data => {
let prettify = pretty($(elements[data]).html());
payload = Object.assing(payload, { data:prettify });
console.log(`${data}: ${prettify}`)
})
return payload
};
If you need to output the entirely object, just change the console.log to console.log(payload)

Related

How to destructure and reassign in one line using JavaScript [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 1 year ago.
I have an object adData and I need to extract some of it's properties, add some more properties to the extracted object and pass the object as parameter. I can do this using:
const params = {};
params.id = adData.id;
params.status = adData.status;
params.frequency = adData.frequency;
params.user = getLoggedInUser();
callAnotherFunction(params)
Can I do the destructing and reassigning to new object in one line ? Something like:
const params = {id, status, frequency} = adData;
params.user = getLoggedInUser();
Or
const params = {id, status, frequency, getLoggedInUser(): user} = adData;
Now these both above syntaxes are wrong but is there any other way to do it using destructuring and without extracting the properties one by one
If you know what properties the object does have, and there aren't that many, you can list them and use rest syntax to gather the others into an object:
const { unwantedProp, ...params) = adData;
// use params
Otherwise, there isn't any incredibly simple syntax for what you want, though you could
const params = Object.fromEntries(
Object.entries(adData).filter(([key]) =>
['id', 'status', 'frequency'].includes(key)
)
);
We can do in one line with destructuring and arrow function.
const getLoggedInUser = () => "foo";
const adData = {
id: 123,
status: "active",
frequency: "less",
bar: 4,
};
const params = (({ id, status, frequency }, user = getLoggedInUser()) => ({
id,
status,
frequency,
user,
}))(adData);
console.log({ params });

Object.assign can`t find declared variable [duplicate]

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);

Combine array of objects into a single object [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);

JavaScript: Dynamically generated object key [duplicate]

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);

Array values are lost after for loop in NodeJS and Promise (JavaScript) [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am having issues with how to handle data in an async fashion with Promises.
I have created a function that takes in a PDF stream and using pdf.js parses the document, pages and annotations to extract the values I need in an Array format.
The issue is that after I loop through the pages, and each annotation element, I am unable to update the outer scope variable.
The goal is to have dataArray populated with the records of each element of each page in the PDF document.
My codes is as below:
const pdfjs = require('pdfjs-dist');
function parsePdf(data) {
let dataArray = [];
pdfjs.getDocument(data)
.then(pdf => {
for (let i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i)
.then(page => {
page.getAnnotations()
.then(items => {
items.forEach(element => {
let obj = {};
if (element.fieldName) {
obj.id = element.id;
obj.name = element.fieldName;
obj.value = element.fieldValue;
obj.isCheckbox = element.checkBox;
obj.isRadioButton = element.radioButton;
obj.isReadOnly = element.readOnly;
obj.type = element.fieldType;
dataArray.push(obj);
}
});
// Return values See example 1 below
console.log(dataArray);
});
});
}
});
// Returns Empty Array []
console.log(dataArray);
return dataArray;
}
I'd like to understand I I can get the values returned in the inner forEach scope to the outer variable in the function. I know it has to do with how Promises are handling the response but I just can't figure out how to chain the .then() code.
Example of what comes back in each console.log(dataArray)
[
{ id: '59R',
name: 'Name_es_:signer:signature',
value: 'Jon Doe',
isCheckbox: undefined,
isRadioButton: undefined,
isReadOnly: false,
type: 'Tx' },
{ id: '62R',
name: 'Address',
value: '1 Main Street',
isCheckbox: undefined,
isRadioButton: undefined,
isReadOnly: false,
type: 'Tx' }
]
Thank you for your help!

Categories