gray-matter icon indicating copy to clipboard operation
gray-matter copied to clipboard

Reference issue

Open viethung0823 opened this issue 8 months ago • 0 comments

function updateFrontMatter(template, field, value, isArray = false) {
	const matterValue = matter(template);
	if (isArray) {
		matterValue.data[field] = [...matterValue.data[field], ...value.split(",").map((v) => v.trim())];
	} else {
		matterValue.data[field] = value;
	}
	const updatedTemplate = matter.stringify(matterValue.content, matterValue.data);
	return updatedTemplate;
}
// the templates are the same at first
let firstTemplate = '---\nfield: ["original value"]\n---\ncontent';
let secondTemplate = '---\nfield: ["original value"]\n---\ncontent';
for (let i = 0; i < 2; i++) {
	firstTemplate = updateFrontMatter(firstTemplate, "field", `new value for firstTemplate ${i}`, true);
	console.log("firstTemplate \n", firstTemplate);
}
secondTemplate = updateFrontMatter(secondTemplate, "field", "new value for secondTemplate", true);
console.log("secondTemplate", secondTemplate);

LOG:

firstTemplate 
 ---
field:
  - original value
  - new value for firstTemplate 0
---
content

firstTemplate 
 ---
field:
  - original value
  - new value for firstTemplate 0
  - new value for firstTemplate 1
---
content

secondTemplate ---
field:
  - original value
  - new value for firstTemplate 0
  - new value for secondTemplate
---
content

Can anyone explain for me why at 2nd template value it has value from the 1st one? The line matterValue from const matterValue = matter(template); always return a new ref right?

viethung0823 avatar May 30 '24 12:05 viethung0823